views:

65

answers:

3

I'm using cURL to parse a website.

http://www.hcmiu.edu.vn/bookforsale/showbooks.php

It need session to view, if you don't have session then the page redirect to :

http://www.hcmiu.edu.vn/bookforsale/perInfo.php

I use this code to get session cookie but I don't know why I cannot see any change to file cookies.txt

$urltopost = "http://www.hcmiu.edu.vn/bookforsale/perInfo.php";
$datatopost = array (
"name" => "abc",
"tel" => "99999999",
"email" => "[email protected]",
"profession" => "abc",
"employer" => "abc",
"tel_work" => "99999999",
); 
$ch = curl_init($urltopost);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datatopost);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookies.txt"); 

$returnData = curl_exec($ch);
$file = fopen("example.txt", "w");
fwrite($file, $returnData);
fclose($file);
curl_close($ch);

However, I see:

Set-Cookie: PHPSESSID=1egb993objkrdp3gi5mpvs02g0; path=/ 

in the header. Thanks for any help

-Edit: I use a tricky way: I use http viewer to view the PHPSESSID in browser cookies. And then I use it to to create a cookies file for cURL to read. Then I could pass the session checking of the web server for viewing file showbooks.php .

+1  A: 

is the file writable? does it even exist?

sathia
the file is unexisted. But if it's existed, it also isn't written any cookies data.
coolkid
+1  A: 

Try creating the file and give it global read write privilege.

Also try with a relative path (say, ./cookies.txt) instead of an absolute path for the cookie jar file.

Joyce Babu
the file is also empty.
coolkid
+1  A: 

I used this code snippet to extract the cookie from the server's response:

$returnData = curl_exec($ch);
$cookie = '';
$pattern = '/Set-Cookie:(.*?)\n/';
if (preg_match($pattern, $returnData, $result))
$cookie = $result[1];

I've described my experience in this post. This approach doesn't use cookie file.


What concerns cookie file, consider the following advice from http://php.net/manual/en/book.curl.php:

Use absolute path for setting the variables CURLOPT_COOKIEFILE & CURLOPT_COOKIEJAR. To make life easier use the realpath("file.txt") function to get the absolute path.

Kniganapolke
thanks, your solution help me a lot. I don't know why some tutorials on internet does not comment about this problem.
coolkid
I'm glad this helped.
Kniganapolke