Method steps for passing cookie in PHP CURL

  • 2021-12-11 07:15:22
  • OfStack

How to use cookie of curl? Beginners have a headache. There are too many parameters in curl, among which four are involved in cookie.

Of course, there are three cookie of curl written clearly in the manual, but there is also a parameter of header, which can include cookie.

curl is very easy to use. The most important thing is to be familiar with the usage of curl_setopt.


curl_setopt ($ch, CURLOPT_COOKIE , $cookie );

The cookie value here should be used; Separate, not with & . You don't need to encode it with urlencode. Of course, it is better to encode it.


$cookie = "a=b;c=d;name= Fang Shiyu ";

Note that when using this, it is not allowed in curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);

Include the Cookie parameter in $header of, otherwise it will overlap, causing the unforeseen situation of cookie to occur.


<? php
$url = "http://www.test.com/zzzz.php";
$post_data = array (
  "foo" =< "bar",
  "query" =< "Nettuts",
  "action" =< "Submit"
);
$cookie_jar_index = 'f:/js/test/cookie.txt';
$cookie = "a=b;c=d;name= Fang Shiyu ";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//  We're in POST Data! 
curl_setopt($ch, CURLOPT_POST, 1);
//  Put post Variables of plus 
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
$output = curl_exec($ch);
curl_close($ch);
echo $output;

Attached is the code used to analyze cookie in IE


<? php
function join_cookie($cook)
{
  foreach( $cook as $k=<$v )
  {
  $d[] =$k."=".$v;
  }
$data = implode(";",$d);
return $data;
}
function pase_cookie($cookFile,$encode=true)
{
$cookie = file_get_contents ( $cookFile );
$citem = explode("*\n",$cookie);
foreach( $citem as $c )
{
list($ckey,$cvalue) = explode("\n",$c);
if($ckey!='')$cook[$ckey] = $cvalue;
}
return $cook;
}


Related articles: