user5563910
user5563910

Reputation:

How to pass PHP_session_id in curl request

I am learning PHP and trying to automate a website login and then post some data to another page once logged in. I managed to login to the website and when I try to post data, I got a "Document moved".

Then I analysed the headers in firebug and realised that there was a PHP_session_id, so when I tried to manually pass this PHP_session_id it worked.

So my question is, how can I automatically get the sessionid when I login and then subsequently pass this on to my second request?

This is what my code looks like:

<?php
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"http://www.example.com/login-main.php");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,
                "loginType=company&username=johndoe%40gmail.com&password=1234&company=test");

    ob_start();
    curl_exec ($ch);
    ob_end_clean();
    curl_close ($ch);
    unset($ch);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(

    'Host:www.example.com',
    'Origin:http://www.example.com',
    'Cookie:PHPSESSID=na6ivnsdfab206ktb453o2au07',
    'Referer:http://www.example.com/bookings/'

        ));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL,"http://www.example.com/bookings.php");
    curl_setopt($ch, CURLOPT_POSTFIELDS,
                "start_date=&end_date=&type=instructor&b_type=&id=41");
    $buf2 = curl_exec ($ch);
    curl_close ($ch);
    echo "<PRE>".htmlentities($buf2);
?>

Upvotes: 3

Views: 1943

Answers (1)

Dmitriy Antonenko
Dmitriy Antonenko

Reputation: 201

Add to your code in all curl requests

 curl_setopt($ch, CURLOPT_COOKIEJAR, $full_path_to_cookie_file);
 curl_setopt($ch, CURLOPT_COOKIEFILE, $full_path_to_cookie_file); 

For example

$full_path_to_cookie_file= __DIR__.'/cookie.txt';

Upvotes: 1

Related Questions