Using cookies with cURL in PHP

I wrote this up for Stack Overflow when they were trying out the concept of “Documentation” for all sorts of things. It didn’t work out, but I thought I’d post this somewhere.

cURL can keep cookies received in responses for use with subsequent requests. For simple session cookie handling in memory, this is achieved with a single line of code:

curl_setopt($ch, CURLOPT_COOKIEFILE, "");

In cases where you are required to keep cookies after the cURL handle is destroyed, you can specify the file to store them in:

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

Then, when you want to use them again, pass them as the cookie file:

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

Remember, though, that these two steps are not necessary unless you need to carry cookies between different cURL handles. For most use cases, setting CURLOPT_COOKIEFILE to the empty string is all you need.


Cookie handling can be used, for example, to retrieve resources from a web site that requires a login. This is typically a two-step procedure. First, POST to the login page.

<?php

# create a cURL handle
$ch  = curl_init();

# set the URL (this could also be passed to curl_init() if desired)
curl_setopt($ch, CURLOPT_URL, "https://www.example.com/login.php");

# set the HTTP method to POST
curl_setopt($ch, CURLOPT_POST, true);

# setting this option to an empty string enables cookie handling
# but does not load cookies from a file
curl_setopt($ch, CURLOPT_COOKIEFILE, "");

# set the values to be sent
curl_setopt($ch, CURLOPT_POSTFIELDS, [
    "username"=>"joe_bloggs",
    "password"=>"$up3r_$3cr3t",
]);

# return the response body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

# send the request
$result = curl_exec($ch);

The second step (after standard error checking is done) is usually a simple GET request. The important thing is to reuse the existing cURL handle for the second request. This ensures the cookies from the first response will be automatically included in the second request.

# we are not calling curl_init()

# simply change the URL
curl_setopt($ch, CURLOPT_URL, "https://www.example.com/show_me_the_foo.php");

# change the method back to GET
curl_setopt($ch, CURLOPT_HTTPGET, true);

# send the request
$result = curl_exec($ch);

# finished with cURL
curl_close($ch);

# do stuff with $result...

This is only intended as an example of cookie handling. In real life, things are usually more complicated. Often you must perform an initial GET of the login page to pull a login token that needs to be included in your POST. Other sites might block the cURL client based on its User-Agent string, requiring you to change it.

Using cURL in PHP

Basic Usage (GET Requests)

cURL is a tool for transferring data with URL syntax. It support HTTP, FTP, SCP and many others (when using curl >= 7.19.4). Remember, you need to install and enable the cURL extension to use it.

// a little script to check if the cURL extension is loaded or not
if(!extension_loaded("curl")) {
    die("cURL extension not loaded! Quit Now.");
}
 
// Actual script start
 
// create a new cURL resource
// $curl is the handle of the resource
$curl = curl_init();
 
// set the URL and other options
curl_setopt($curl, CURLOPT_URL, "http://www.example.com");
 
// execute and pass the result to browser
curl_exec($curl);
 
// close the cURL resource
curl_close($curl);

// a little script to check if the cURL extension is loaded or not if(!extension_loaded("curl")) { die("cURL extension not loaded! Quit Now."); } // Actual script start // create a new cURL resource // $curl is the handle of the resource $curl = curl_init(); // set the URL and other options curl_setopt($curl, CURLOPT_URL, "http://www.example.com"); // execute and pass the result to browser curl_exec($curl); // close the cURL resource curl_close($curl);

Using Cookies

cURL can keep cookies received in responses for use with subsequent requests. For simple session cookie handling in memory, this is achieved with a single line of code:

curl_setopt($ch, CURLOPT_COOKIEFILE, "");

curl_setopt($ch, CURLOPT_COOKIEFILE, "");

In cases where you are required to keep cookies after the cURL handle is destroyed, you can specify the file to store them in:

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

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

Then, when you want to use them again, pass them as the cookie file:

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

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

Remember, though, that these two steps are not necessary unless you need to carry cookies between different cURL handles. For most use cases, setting CURLOPT_COOKIEFILE to the empty string is all you need.


Cookie handling can be used, for example, to retrieve resources from a web site that requires a login. This is typically a two-step procedure. First, POST to the login page.

<?php
 
# create a cURL handle
$ch = curl_init();
 
# set the URL (this could also be passed to curl_init() if desired)
curl_setopt($ch, CURLOPT_URL, "https://www.example.com/login.php");
 
# set the HTTP method to POST
curl_setopt($ch, CURLOPT_POST, true);
 
# setting this option to an empty string enables cookie handling
# but does not load cookies from a file
curl_setopt($ch, CURLOPT_COOKIEFILE, "");
 
# set the values to be sent
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    "username" => "joe_bloggs",
    "password" => "$up3r_$3cr3t",
));
 
# return the response body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
# send the request
$result = curl_exec($ch);

<?php # create a cURL handle $ch = curl_init(); # set the URL (this could also be passed to curl_init() if desired) curl_setopt($ch, CURLOPT_URL, "https://www.example.com/login.php"); # set the HTTP method to POST curl_setopt($ch, CURLOPT_POST, true); # setting this option to an empty string enables cookie handling # but does not load cookies from a file curl_setopt($ch, CURLOPT_COOKIEFILE, ""); # set the values to be sent curl_setopt($ch, CURLOPT_POSTFIELDS, array( "username" => "joe_bloggs", "password" => "$up3r_$3cr3t", )); # return the response body curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); # send the request $result = curl_exec($ch);

The second step (after standard error checking is done) is usually a simple GET request. The important thing is to reuse the existing cURL handle for the second request. This ensures the cookies from the first response will be automatically included in the second request.

# we are in the same scope, and not calling curl_init()

# simply change the URL
curl_setopt($ch, CURLOPT_URL, "https://www.example.com/show_me_the_foo.php");
 
# change the method back to GET
curl_setopt($ch, CURLOPT_HTTPGET, true);
 
# send the request
$result = curl_exec($ch);
 
# finished with cURL
curl_close($ch);
 
# do stuff with $result...

# we are in the same scope, and not calling curl_init() # simply change the URL curl_setopt($ch, CURLOPT_URL, "https://www.example.com/show_me_the_foo.php"); # change the method back to GET curl_setopt($ch, CURLOPT_HTTPGET, true); # send the request $result = curl_exec($ch); # finished with cURL curl_close($ch); # do stuff with $result...

This is only intended as an example of cookie handling. In real life, things are usually more complicated. Often you must perform an initial GET of the login page to pull a login token that needs to be included in your POST. Other sites might block the cURL client based on its User-Agent string, requiring you to change it.

This content is copied from Stack Overflow Documentation, a beta program which ended in 2017. All content was authored solely by myself. https://web.archive.org/web/20170816194237/https://stackoverflow.com/documentation/php/701/using-curl-in-php#t=201708161942371592047

PHP fatal errors in imagepng()

I upgraded to PHP 5.2 from 4.3 recently and came across a couple of error messages: php[7028], PHP Warning: imagepng(): gd-png: fatal libpng error: zlib error in … followed by: php[7028], PHP Warning: imagepng(): gd-png error: setjmp returns error condition in …

Turns out the paramters for imagepng changed in PHP 5.1.3, and I’m not sure what the third argument used to be, but where I had imagepng($image, null, 100) it died, because the third argument (quality) is supposed to be 0 to 9 now.

I came across postings saying to replace DLL files and all this nonsense, but all I needed to do was change the 100 to a 9.

Using PHP to interface with WMI

Windows Management Instrumentation (WMI) is a Windows derivative of the WBEM standard allowing centralized management of a wide number of Windows functions. There is almost no mention of how to use it from PHP, although combined together they provide a powerful method of web-based management. This example shows how to connect to a remote server, update a single DNS record, then flush the DNS cache.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
< ?php
$host = 'www';
$ip = '192.168.1.1';
$domain = 'example.com';
$query = "SELECT * FROM MicrosoftDNS_AType WHERE DomainName='$domain' AND OwnerName='$host.$domain'"; 
try {
//create the object
	$rpc = new COM('WbemScripting.SWbemLocator');
//update DNS
	$wmi = $rpc->ConnectServer($rpchost, 'Root/MicrosoftDNS', $user, $pass);
	$hosts = $wmi->ExecQuery($query);
	foreach($hosts as $host) {
		echo "Updating $host->OwnerName from $host->IPAddress to $ip.";
		flush(); ob_flush();
		$result = new Variant(null);
		$host->Modify(null, $ip, $result);
	}
//flush the DNS cache by restarting the dnscache service
	$query = "SELECT * FROM Win32_Service WHERE Name='Dnscache'";
	$wmi = $rpc->ConnectServer($rpchost, 'Root/cimv2', $user, $pass);
	$services = $wmi->ExecQuery($query);
	foreach ($services as $service) {
		$service->StopService();
		sleep(2);
		$service->StartService();
	}
}
catch(Exception $e) {
	echo $e;
	exit;
}?>

< ?php $host = 'www'; $ip = '192.168.1.1'; $domain = 'example.com'; $query = "SELECT * FROM MicrosoftDNS_AType WHERE DomainName='$domain' AND OwnerName='$host.$domain'"; try { //create the object $rpc = new COM('WbemScripting.SWbemLocator'); //update DNS $wmi = $rpc->ConnectServer($rpchost, 'Root/MicrosoftDNS', $user, $pass); $hosts = $wmi->ExecQuery($query); foreach($hosts as $host) { echo "Updating $host->OwnerName from $host->IPAddress to $ip."; flush(); ob_flush(); $result = new Variant(null); $host->Modify(null, $ip, $result); } //flush the DNS cache by restarting the dnscache service $query = "SELECT * FROM Win32_Service WHERE Name='Dnscache'"; $wmi = $rpc->ConnectServer($rpchost, 'Root/cimv2', $user, $pass); $services = $wmi->ExecQuery($query); foreach ($services as $service) { $service->StopService(); sleep(2); $service->StartService(); } } catch(Exception $e) { echo $e; exit; }?>

A couple of points to note:

  1. this is PHP 5 code, it will not work in version 4.
  2. This code uses the COM functions, only available in Windows-based PHP installs.
  3. notice that even though I only pulled one record from the WMI server, I still have to use foreach to iterate through the result set. Like the query itself, the result set is treated the same as one from a database.
  4. I needed to reconnect after the DNS update to use a new namespace; where the DNS server management classes are in the Root/MicrosoftDNS namespace, the service management classes are in the default Root/cimv2 namespace.
  5. Microsoft’s WMI documentation is here. All the code samples are VBScript, but using the example above you should be able to figure things out.