user3065191
user3065191

Reputation: 145

PHP file_get_contents doesn't retrieve cookies

I've read some topics about this problem..and some people says to use cURL (althought I don't know how..)

I have two files, index.php and response.php.

index.php

/* After the body tag, in the middle of screen */
<?php echo file_get_contents('http://localhost/football/classes/response.php?type=clients'); ?>

This code was working perfectly until I realize that I need to retrieve the same info, but with cookies, when the page loads.

My old response.php file was this:

switch($_REQUEST['type']){
    case 'clients':
        $content = $load->clients();
        echo $content;
        break;
}

But now I need to do the same code but with a parameter, inside the function clients(). This parameter is a cookie.

switch($_REQUEST['type']){
    case 'clients':
        $display = 0;
        if(isset($_COOKIE['display'])){ 
            $display = 1;
        }
        $content = $load->clients($display);
        echo $content;
        break;
}

I do always receive $display = 0; because PHP doesn't detect the cookie. Although, this cookie is initialized in Chrome Cookies. Even if I do var_dump($_COOKIE); I still don't receive nothing.

I know that this problem is because of file_get_contents() How can I solve this problem?

Thanks.

Edit: Tried the @Martin solution, without success. file_get_contents receive cookies

<?php 
    $ckfile = tempnam ("/tmp", "CURLCOOKIE");
    $ch = curl_init ("http://localhost/football/index.php");
    curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec ($ch);

    $ch = curl_init ("http://localhost/football/classes/response.php?type=clients");
    curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile); 
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec ($ch);

    echo $output;
?>

The page keeps on looping and doesn't stop. It shows nothing.

Upvotes: 0

Views: 763

Answers (1)

Martin
Martin

Reputation: 2028

The super global $_COOKIE only contains the cookies that your visitor sent to your Web server when it requested your page, it will never contain the cookies that another server may send to your application when it loads another page.

But you can still retrieves all the response headers using $http_response_header.

More info in the PHP doc : $http_response_header

Upvotes: 1

Related Questions