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, "");
// execute and pass the result to browser
// close the cURL resource

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, "");

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.

# 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, "");
# 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, "");
# change the method back to GET
curl_setopt($ch, CURLOPT_HTTPGET, true);
# send the request
$result = curl_exec($ch);
# finished with cURL
# 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.

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.

< ?php
$host = 'www';
$ip = '';
$domain = '';
$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) {
catch(Exception $e) {
	echo $e;

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.