note 70043 deleted from function.curl-setopt by danbrown

From: Date: Mon, 20 Jun 2011 14:53:16 +0000
Subject: note 70043 deleted from function.curl-setopt by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-180691@lists.php.net to get a copy of this message
Note Submitter: zarko at svetlozar dot net ---- As Yevgen mentioned earlier sometimes we can't use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE. Below is a header callback function I wrote back in January that lets you maintain cookies between cURL requests. Cookies are added to $ch during all requests even during redirection, so you can use it together with CURLOPT_FOLLOWLOCATION. Here is the code: <?php function read_header($ch, $string) { global $location; #keep track of location/redirects global $cookiearr; #store cookies here global $ch; # ^overrides the function param $ch # this is okay because we need to # update the global $ch with # new cookies $length = strlen($string); if(!strncmp($string, "Location:", 9)) { #keep track of last redirect $location = trim(substr($string, 9, -1)); } if(!strncmp($string, "Set-Cookie:", 11)) { #get the cookie $cookiestr = trim(substr($string, 11, -1)); $cookie = explode(';', $cookiestr); $cookie = explode('=', $cookie[0]); $cookiename = trim(array_shift($cookie)); $cookiearr[$cookiename] = trim(implode('=', $cookie)); } $cookie = ""; if(trim($string) == "") { #execute only at end of header foreach ($cookiearr as $key=>$value) { $cookie .= "$key=$value; "; } curl_setopt($ch, CURLOPT_COOKIE, $cookie); } return $length; } ?> Using the header function with curl (add this before curl_exec): <?php #don't forget globals, especially if you are using this in function curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header'); ?> This code assumes that you will reuse $ch without initializing it every time (call curl_init only once, in the beginning). If you need to initialize $ch again at any point in your code you can access the currently stored cookies in $cookiearr and include them in the new $ch. I wrote this function before I had enough experience with regular expressions so you won't find any preg_match calls here. I have used this code for quite a while and without any problems accessing gmail, yahoo, hotmail, aol etc. where I had to go through login and a few pages before getting to what I was looking for. Svetlozar Petrov (http://svetlozar.net)

« previous php.notes (#180691) next »