A
A
andreys752014-03-25 08:08:02
PHP
andreys75, 2014-03-25 08:08:02

How to pass cookies with second request in cUrl?

Good afternoon!
Task: get a page from a remote server through a php script. Registration is required to log in to a remote server.
I solve the problem using curl
1. I execute the first request to log in

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL,  $q);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $p);

curl_setopt($ch, CURLOPT_COOKIEFILE, $_SERVER["DOCUMENT_ROOT"]."/cookies1.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, $_SERVER["DOCUMENT_ROOT"]."/cookies1.txt");


 $content = curl_exec ($ch);

The request is executed correctly, $content contains the page I need after logging in to the remote server
. The problem is this: I need to execute the next post request, but in the same session (because I have already logged in). Those. I need to pass cookies in the next request.
In the first request, the cookie1.txt file has been generated, and the session value is there.
I need to add 3 more parameters to this value and then pass them to the new request. To begin with, I want to pass at least the session value that I received from the first request.
I execute exactly the same request, but with a different value of the post request fields
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL,  $q);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $p);

curl_setopt($ch, CURLOPT_COOKIEFILE, $_SERVER["DOCUMENT_ROOT"]."/cookies1.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, $_SERVER["DOCUMENT_ROOT"]."/cookies1.txt");


 $content = curl_exec ($ch);

I look in firebug what is being passed, and I see that no cookies were passed in the second request.
If I use the setcookie operator, then everything works.
Question:
1. Why are cookies not being passed in the second request?
2. Is there any function to read cookie values ​​from a file and then set them (don't want to reinvent the wheel, I understand that I can read cookies1.txt, parse it and set it via setcookie)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Prilepa, 2014-03-25
@OAPrilepa

Old code, log in and get cookies in a string:

// Отправка POST запроса с получением печенек:
function send_post_get_cookie($URL='', $PostData=Array(), $cookie='')
{
    // Отсекаем пустые вызовы:
    if (strlen($URL)<=0) return false;
    // Скопировал строку из FireBug:
    $ua = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.13) Gecko/20101203 MRA 5.7 (build 03796) Firefox/3.6.13';
    // Инициализация объекта:
    $ch = curl_init($URL);
    // показывать заголовки (в них куки):
    curl_setopt($ch, CURLOPT_HEADER, 1); 
    // не показывать тело страницы (для экономии траффика):
    curl_setopt($ch, CURLOPT_NOBODY, 1); 
    // это чтобы прикинуться браузером:
    curl_setopt($ch, CURLOPT_USERAGENT, $ua);
    // можно ставить еще вот это, если удаленный сервер проверяет:
    // curl_setopt($ch, CURLOPT_REFERER, $URL);
    curl_setopt($ch, CURLOPT_POST, 1);
    // включение полей POST в запрос:
    curl_setopt($ch, CURLOPT_POSTFIELDS, $PostData);
    // если нужны печеньки, установим:
    if (strlen($cookie)>0)
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    // тормозим стандартный вывод:
    ob_start();
    // запускаем запрос:
        curl_exec ($ch);
        curl_close ($ch);
        // получаем заголовки в массив:
        $headers = explode("\n", ob_get_contents());
    ob_end_clean();
    // выдираем строку печенек:
    for ($i=0, $cnt=count($headers); $i<$cnt; $i++) 
        if (strpos($headers[$i], 'Set-Cookie:') !== FALSE)
            $cookie .= substr($headers[$i], strpos($headers[$i], 'Set-Cookie:')+strlen('Set-Cookie:')); 
    // и возвращаем результат:
    return $cookie;
}

And then we use it in other requests, for example, we upload a file after authorization:
// Сохранение файла с удаленного хостинга:
function save_get_file($URL='', $cookie='')
{
    if (strlen($URL)<=0) return false;
    $filename = $_SERVER['DOCUMENT_ROOT'].'/upload/tmp/'.date('YmdHis_').rand(99,9999999).'.tmp'; 
    $fp = fopen($filename, 'w');
    if (!$fp)
        return false;
    else
    {
        $ua = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.13) Gecko/20101203 MRA 5.7 (build 03796) Firefox/3.6.13';
        $ch = curl_init($URL);
        curl_setopt($ch, CURLOPT_USERAGENT, $ua);
        curl_setopt($ch, CURLOPT_FILE, $fp); // чтобы выгрузить в файл;
        if (strlen($cookie)>0)
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        curl_exec ($ch);
        curl_close ($ch);
        return $filename;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question