13.3 Eine URL mit Cookies abrufen

Problem

Sie möchten eine Seite abrufen, bei der ein Cookie zusammen mit der Seitenanfrage übersandt werden muss.

Lösung

Verwenden Sie file_get_contents() mit einem Stream-Kontext:

$contextOptions = array(
    "http" =>
        array ("header"
            => "Cookie: user=ellen; activity=schwimmen\r\n"));
$context = stream_context_create($contextOptions);
$page = file_get_contents("http://www.example.com/braucht-cookies.php", false, $context);

Alternativ können Sie die cURL-Erweiterung und die Option CURLOPT_COOKIE verwenden:

$c = curl_init('http://www.example.com/braucht-cookies.php'); curl_setopt($c, CURLOPT_VERBOSE, 1); curl_setopt($c, CURLOPT_COOKIE, 'user=ellen; activity=schwimmen'); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); $page = ...

Get PHP 5 Kochbuch now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.