Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 558
Hazem Hagrass Avatar asked Jan 18 '26 12:01

Hazem Hagrass


2 Answers

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.

like image 153
3 revsInfinite Recursion Avatar answered Jan 21 '26 04:01

3 revsInfinite Recursion


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;
}
like image 27
Hazem Hagrass Avatar answered Jan 21 '26 04:01

Hazem Hagrass



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!