Using cURL in PHP

-

In Creating a Reddit front page generator, we used fopen to get the response from a server. Similar methods are file_get_contents, file, and read. They can all take a full URL as a parameter.

These methods can be used to easily send GET variables, but fail to provide the flexibility of POST data and error reporting. For these reasons, the preferred method is using cURL. With cURL, we can set the protocol and other options.

Basic usage of cURL

cURL is fairly straightforward. We initialize cURL with curl_init(), execute with curl_exec, and close with curl_close.

Quick example:

<?
// Initialize cURL
$ch = curl_init("https://www.apptic.me/");

// Execute the request (prints to the screen)
curl_exec($ch);

// Close cURL
curl_close($ch);
?>

This code simply prints the response (in this case, an HTML file) from the server.

Setting options

Before executing, we can set the options that we need. The full list is available in the documentation. We'll cover some of the common ones.

Getting the response as a string

For example, rather than printing to the screen, we might want the output as a string.

<?
$ch = curl_init("https://www.apptic.me/");

// Set some options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the request (now it is returned as a string)
$output = curl_exec($ch);

curl_close($ch);
?>

Error checking

You might find that you're getting no response, or some other error is occurring. You can easily check for errors.

<?
$ch = curl_init("https://www.apptic.me/");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$output = curl_exec($ch);

// If cURL fails, find out why
if ($output === false){
    curl_error($ch);
}

curl_close($ch);
?>

Setting the URL through the options

<?
$ch = curl_init();

// Set the URL
curl_setopt($ch, CURLOPT_URL, "https://www.apptic.me/");

curl_exec($ch);

curl_close($ch);
?>

Sending POST data

When you receive POST data, it comes in the form of an array; likewise, to send POST data, we pass cURL an array.

<?
$post_data = array (
    "sample" => "post",
    "name" => "data"
);
 
$ch = curl_init("http://www.example.com/some-form.php");

// let cURL know we will send POST data
curl_setopt($ch, CURLOPT_POST, true);
// send our POST array
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
 
curl_exec($ch);
 
curl_close($ch);
?>

Conclusion

Those are the basics of cURL. The library has tons of features - you can access a URL through a proxy, upload files, and so much more. This should be enough to get you started!

Tags: cURL fetch php api

See also: Creating a Reddit front page generator

Back to all posts

Neel Somani

About the Author

Neel Somani, a student at the University of California, Berkeley, is the founder of Apptic LLC. In addition to computer science, he's interested in philosophy and entrepreneurship. You can follow him on LinkedIn and Twitter.

comments powered by Disqus