You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中获取并显示任意远程URL的所有Cookie值?

Hey there! Let's break down how you can build that cookie-checking functionality similar to the site you mentioned. Your initial approach is totally on the right track—using an HTTP client to send a request and extract response cookies is exactly how this works. Let's refine that idea into a more robust, user-friendly implementation.

Core Implementation (Based on Your Initial Code)

Your base code can be expanded to handle edge cases and present cookies in a readable way. Here's an improved version:

// Ensure you have the HTTP_Request package installed (via PECL or Composer)
require_once 'HTTP/Request.php';

function getRemoteCookies($url) {
    try {
        // Initialize the request to the target URL
        $req = new HTTP_Request($url);
        $req->setMethod(HTTP_REQUEST_METHOD_GET);
        
        // Send the request and capture the response code
        $responseCode = $req->sendRequest();
        
        // Handle non-success HTTP status codes
        if ($responseCode !== 200 && $responseCode !== 302) {
            return "Failed to load URL: HTTP status code $responseCode";
        }
        
        // Retrieve cookies from the server's response
        $cookies = $req->getResponseCookies();
        
        if (empty($cookies)) {
            return "No cookies found for this URL.";
        }
        
        // Format cookies into a user-friendly list
        $displayOutput = "<ul>";
        foreach ($cookies as $cookie) {
            $displayOutput .= sprintf(
                "<li><strong>Name:</strong> %s<br>
                 <strong>Value:</strong> %s<br>
                 <strong>Domain:</strong> %s<br>
                 <strong>Path:</strong> %s<br>
                 <strong>Expires:</strong> %s</li>",
                htmlspecialchars($cookie['name']),
                htmlspecialchars($cookie['value']),
                htmlspecialchars($cookie['domain'] ?? 'N/A'),
                htmlspecialchars($cookie['path'] ?? '/'),
                isset($cookie['expires']) ? date('Y-m-d H:i:s', $cookie['expires']) : 'Session'
            );
        }
        $displayOutput .= "</ul>";
        
        return $displayOutput;
    } catch (Exception $e) {
        return "Error: " . htmlspecialchars($e->getMessage());
    }
}

// Example usage
$targetUrl = "https://example.com";
echo getRemoteCookies($targetUrl);

Key Things to Keep in Mind

  • Dependency Setup: You'll need to install the HTTP_Request package first. If you prefer a more modern alternative, consider using Guzzle (a widely maintained HTTP client) instead—more on that below.
  • Error Handling: Added try/catch blocks and HTTP status checks to handle unreachable URLs, server errors, or empty cookie responses.
  • Security: Used htmlspecialchars() to prevent XSS attacks when displaying cookie values to end users.
  • Readability: Replaced raw print_r() output with a structured list that highlights important cookie details like domain, path, and expiration.

Alternative: Modern Approach with Guzzle

If you want a more up-to-date tool, Guzzle is a great choice. Here's a quick implementation:

require 'vendor/autoload.php';
use GuzzleHttp\Client;

function getRemoteCookiesGuzzle($url) {
    try {
        $client = new Client();
        $response = $client->request('GET', $url);
        
        // Extract raw Set-Cookie headers from the response
        $cookieHeaders = $response->getHeaders()['Set-Cookie'] ?? [];
        
        if (empty($cookieHeaders)) {
            return "No cookies found for this URL.";
        }
        
        // Parse and format cookies for display
        $displayOutput = "<ul>";
        foreach ($cookieHeaders as $cookieString) {
            $cookieParts = explode(';', $cookieString);
            $cookieData = [];
            
            foreach ($cookieParts as $part) {
                $part = trim($part);
                if (strpos($part, '=') !== false) {
                    list($key, $value) = explode('=', $part, 2);
                    $cookieData[strtolower($key)] = $value;
                } else {
                    $cookieData[strtolower($part)] = true;
                }
            }
            
            $displayOutput .= sprintf(
                "<li><strong>Name:</strong> %s<br>
                 <strong>Value:</strong> %s<br>
                 <strong>Domain:</strong> %s<br>
                 <strong>Path:</strong> %s<br>
                 <strong>Expires:</strong> %s</li>",
                htmlspecialchars($cookieData['name'] ?? 'N/A'),
                htmlspecialchars($cookieData['value'] ?? 'N/A'),
                htmlspecialchars($cookieData['domain'] ?? 'N/A'),
                htmlspecialchars($cookieData['path'] ?? '/'),
                isset($cookieData['expires']) ? $cookieData['expires'] : 'Session'
            );
        }
        $displayOutput .= "</ul>";
        
        return $displayOutput;
    } catch (Exception $e) {
        return "Error: " . htmlspecialchars($e->getMessage());
    }
}

内容的提问来源于stack exchange,提问作者Chetan Soni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:34:55