3

I need to login (make post) with curl in php to a website, then save a cookie with authentication, and use it to visit normal link from same website.

They have only half of text available in free version, but the whole in premium. So if it's possible, I would like to save a cookie for multiple times later.

I know something about cURL and PHP, but I've didn't come up with a solution yet.

Thanks guys!

NetStarter
  • 3,189
  • 7
  • 37
  • 48
marc_s
  • 1,007
  • 3
  • 14
  • 24
  • 1
    Good question. I've wondered this a few times, but never actually found out the answer. – Jonathan May 22 '13 at 07:08
  • **Login to page with curl in php and then visit link “logged in”** i think this line at the top of the question is bit enough to say what the OP wants @Jonathan – NetStarter May 22 '13 at 07:12
  • 1
    @NetStarter Yes. You're right. I removed my comment after I had thought for a bit. :) – Jonathan May 22 '13 at 07:14

1 Answers1

6

You need to use the cookiejar parameter to share a text file between both requests.

/* Create a temporary cookie file */
$ckfile = tempnam ("/tmp", "COOKIES");

/* Visit the first page */

$ch = curl_init ("http://somedomain.com/");
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);

/* Visit the second page */

$ch = curl_init ("http://somedomain.com/cookiepage.php");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);

Example modified from http://coderscult.com/php-curl-cookies-example/


Edit: I should have read the docs for tempnam... It creates a unique filename, so adding an additional user specific prefix is not necessary unless you want to be able to identify the file later. You can also look at tmpfile() which is automatically removed when fclose is called (normally at the end of the php request).

Brady Emerson
  • 4,769
  • 1
  • 15
  • 17