• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / PHP CURL and Cookies

PHP CURL and Cookies

PHP’s CURL functions make it easy to download content from websites. Sometimes you need to be able to manage cookies set from the site the data is coming from. This is done using the CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE options as shown in this post.

CURLOPT_COOKIEJAR

CURLOPT_COOKIEJAR species the filename where the cookies should be stored. If the server sets any they will be written to this file, and it will be created if it does not already exist.

To set the cookie file as /tmp/cookies.txt (which is not really a good place to store the cookie file, but will serve for this example), to the curl handle $ch:

curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');

CURLOPT_COOKIEFILE

The cookie jar setting is where curl writes cookies to, but a separate setting is required for curl to send cookies back to the server. This is the CURLOPT_COOKIEFILE setting. If it is not set then no cookies will be sent to the server. If the file does not exist, then no error is issued.

Example usage:

curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt');

Putting it all together

The following piece of code reads and writes cookies to the /tmp/cookies.txt file when making a request to http://www.example.com:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt');

$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

The HTML from the request is stored in $output and an array of information about the request is stored in the $info variable. I’ve covered these two variables in a couple of my previous posts about PHP and curl.

Check Out These Related posts:

  1. Setting cookies with jQuery
  2. Cookies and domains
  3. Selectively delete cookies in Firefox
  4. Log into the Google Analytics API using PHP and CURL using Username/Password Authentication

Filed Under: PHP

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap