Hazem Hagrass
Hazem Hagrass

Reputation: 9838

How to make file_get_contents session aware?

I have a php script that will make a series of requests on a server. The first request will be a login request.

The problem is that file_get_contents seems to create a new session every time, so how can I make it session aware?

Here is my function which needed to make it remember session:

function request($method, $data, $url){
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n"."Cookie: ".session_name()."=".session_id()."\r\n",
            'method'  => $method,
            'content' => http_build_query($data),
        ),
    );

    $context  = stream_context_create($options);
    session_write_close();
    $result = file_get_contents($url, false, $context);

    return $result;
}

Upvotes: 3

Views: 1652

Answers (2)

Hazem Hagrass
Hazem Hagrass

Reputation: 9838

I just used curls instead of file_get_contents and everything works well with me:

function request_url($method='get', $vars='', $url) {
    $ch = curl_init();
    if ($method == 'post') {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies/cookies.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies/cookies.txt');
    $buffer = curl_exec($ch);
    curl_close($ch);
    return $buffer;
}

Upvotes: 1

Infinite Recursion
Infinite Recursion

Reputation: 6557

Explanation of why the cookies work in cURL in Hazem's answer.

Author: Nate I

The magic happens with CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE.

CURLOPT_COOKIEJAR tells cURL to write all internally known Cookies to the specified file. In this case, 'cookies/cookies.txt'. For most users, it's generally recommended to use something like tempnam('/tmp', 'CURLCOOKIES') so you know for sure that you can generate this file.

CURLOPT_COOKIEFILE tells cURL which file to use for Cookies during the cURL request. That's why we set it to the same file we just dumped the Cookies to.

Upvotes: 1

Related Questions