S
S
siroper2020-08-19 16:08:36
PHP
siroper, 2020-08-19 16:08:36

How to correctly pass cookies in php?

Hello. Please tell me where I'm wrong.

Authorization on the site in this way:

function send_post_get_cookie($URL='', $PostData=Array(), $cookie='')
  {
    if (strlen($URL)<=0) return false;
    $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_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1); 
    curl_setopt($ch, CURLOPT_USERAGENT, $ua);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $PostData);
    if (strlen($cookie)>0)
      curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    $result = curl_exec($ch);
    curl_close($ch);
    
    $lines = explode("\n", $result);
    
    for ($i=0, $cnt=count($lines); $i<$cnt; $i++) 
      if (strpos($lines[$i], 'Set-Cookie:') !== FALSE)
        $cookie .= substr($lines[$i], strpos($lines[$i], 'Set-Cookie:')+strlen('Set-Cookie:')); 
    return $cookie;
  }


It turns out this line:
PHPSESSID=kg0m06ko0p1fi3aipi4g3jbb44; path=/ skin=1; expires=Wed, 18-Jul-2029 05:49:51 GMT; Max-Age=281205923


Next, I try to open another page of the same site with the transfer of the above cookies.

function open($URL='', $cook='')
{
    $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_COOKIE, $cook);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    'page'=>'1'
  ));
    $answer = curl_exec($ch);
    curl_close ($ch);
    return $answer;
}


But I get 400 bad request from the server. I suspect that the line with cookies is not correct chtol, tell me uv. programmers please...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2020-08-19
@Stalker_RED

you can get cookies like this:

$result = curl_exec($ch);
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
    parse_str($item, $cookie);
    $cookies = array_merge($cookies, $cookie);
}
var_dump($cookies);
https://stackoverflow.com/a/895858
If you don't need to modify them, you can just write them to a file AND then use that file for next requests.
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

A
AUser0, 2020-08-19
@AUser0

What does the $cook string look like in the open() function?
It should contain only the text " PHPSESSID=kg0m06ko0p1fi3aipi4g3jbb44 ", exclusively and exclusively, and nothing more.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question