PHP cURL Cookies Example

Posted by Mike Lopez under PHP cURL
May 2008
20
01:01pm

Want to learn how to use PHP cURL with Cookies? Well, it’s pretty simple so let’s go see the code but first let’s make a scenario…

Say we have a page called ‘cookiepage.php’ in a particular website that checks for the cookie set by the homepage and will only return the proper output if the cookie exists. How do you do it? Here’s how…

<?php
/* STEP 1. let’s create a cookie file */
$ckfile = tempnam ("/tmp", "CURLCOOKIE");

/* STEP 2. visit the homepage to set the cookie properly */
$ch = curl_init ("http://somedomain.com/");
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);

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

/* here you can do whatever you want with $output */
?>

Just in case you weren’t able to catch what we did in the above example, here’s a short explanation.

  • STEP 1 creates a temporary cookie file using the tempnam() function.
  • STEP 2 loads the homepage and saves the cookie in our temporary cookie file. The key here is this line:

    curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);

  • STEP 3 loads cookiepage.php with the saved cookie with this line:

    curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);

Sleek and simple ei? Hope this PHP cURL Cookie example helped you out!


Share this Post through Social Bookmarking These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • StumbleUpon
  • Technorati
  • YahooMyWeb

Related Posts

Tags: ,

Leave a Reply