Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Use PHP cURL (Examples Included)

INTRODUCTION
SERVER-TO-SERVER TALK

Welcome to a tutorial on how to use PHP Curl. Need to fetch some data using a PHP script? Or make 2 servers talk to each other? cURL is the answer, and this tutorial will walk you through the exact steps of how to use it, examples included – Read on to find out!

I have included a zip file with all the example source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Section A
The Basics

Section B
Basic Usage

Section C
More Examples

Extra
Useful Bits

Extra
Source Code Download

Closing
What’s Next?

SECTION A
THE BASICS & INSTALLATION

Before we dive into the code examples, let us start with the basics – Just what is cURL, what does it do, and how do we install it?

WHAT IS CURL?

cURL is short for client URL, and let me just do a quick quote from the official PHP manual:

cURL allows you to connect and communicate to many different types of servers with many different types of protocols.

WHAT DOES CURL DO?

In the layman terms, cURL is a Swiss Army knife of server-to-server communication. It allows you to create PHP scripts that can:

  • Fetch web pages via HTTP or HTTPS.
  • POST and PUT, just like submitting HTML forms (or Javascript).
  • Accept and create cookies, act like a web browser.
  • Connect with FTP servers, upload and download files.
  • Telnet into a server, run the command line.
  • And even more…

INSTALLATION & SETUP

If you have installed XAMPP, cURL should be bundled and enabled by default. If you are on Linux, you can probably get cURL installed in just a few lines of commands:

sudo apt-get update
sudo apt-get install php-curl
sudo service apache2 restart

Please also verify that the cURL extension is enabled in the php.ini file:

php.ini
extension=curl

Of course, this might differ for the various operating systems – So please do some of your own research if cURL is not enabled on your computer.

SECTION B
BASIC USAGE

Now that we are done with the basic setup and stuff, let us start with the very basics of cURL, by fetching a webpage with it.

THE SCRIPT

1-curl-basic.php
 "https://en.wikipedia.org/wiki/Main_Page",
  CURLOPT_HEADER => false
]);

// (3) EXECUTE CURL
if (!curl_exec($curl)) {
  echo curl_error($curl); // Error message
  echo curl_errno($curl); // Error code
}
 
// (4) CLOSE CURL CONNECTION
curl_close($curl);
?>

THE EXPLANATION

There are probably 4 steps in every common cURL script:

  • Initialize cURL.
  • Set the options, the target URL, POST data and such. There are a ton of possible options and you might want to check out the official PHP manual.
  • Execute the cURL, handle any errors.
  • Close the cURL connection.

Yep, that’s how we use cURL in a nutshell. We will walk through more practical examples below.

SECTION C
MORE EXAMPLES

But of course, cURL is a lot more capable of just fetching a webpage and outputting it. In this section, we will walk through more cURL yoga and examples.

FETCH AND SAVE TO FILE

Need to save the fetched results into a file? Here is how we do it:

2-fetch-save.php
 "https://en.wikipedia.org/wiki/Meme",
  CURLOPT_FILE => $fhandle
]);

// (4) EXECUTE CURL
$result = curl_exec($curl);

// (4A) ERROR
if ($result === false) {
  echo curl_error($curl); // Error message
  echo curl_errno($curl); // Error code
}
// (4B) OK
else {
  echo "OK";
}

// (5) CLOSE CURL CONNECTION + FILE HANDLER
curl_close($curl);
fclose($fhandle);
?>

FETCH DATA & JSON DECODE

As you may already know, we can use cURL to fetch data from an address that we specify. The good news is, the Internet these days offer quite all sorts of interesting things – Weather, news, dictionaries, and even random dog pictures.

3-fetch-json.php
 "https://dog.ceo/api/breeds/image/random",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HEADER => false
]);

// (3) EXECUTE CURL
$result = curl_exec($curl);

// (3A) ERROR
if ($result === false) {
  echo curl_error($curl); // Error message
  echo curl_errno($curl); // Error code
}
// (3B) OK
else {
  $result = json_decode($result, true);
  // print_r($result);
  echo "";
}

// (4) CLOSE CURL CONNECTION
curl_close($curl);
?>

Well, if you are interested in more, you can check out this list on Github for more public APIs.

POST DATA

Need to POST some data to a remote server? We simply add it to the cURL options.

4-curl-post.php
 "Good Boy",
  "cate" => "Evil"
];
curl_setopt_array($curl, [
  CURLOPT_URL => "https://whatever.com/xyz.php",
  CURLOPT_POSTFIELDS => $data,
  CURLOPT_POST => true, // Optional, since CURLOPT_POSTFIELDS will already imply POST
  CURLOPT_RETURNTRANSFER => true // Optional, if you need the remote server response
]);

// (3) EXECUTE CURL
$result = curl_exec($curl);

// (3A) ERROR
if ($result === false) {
  echo curl_error($curl); // Error message
  echo curl_errno($curl); // Error code
}
// (3B) OK
else {
  echo $result;
}

// (4) CLOSE CURL CONNECTION
curl_close($curl);
?>

GET INSTEAD OF POST

To add GET data, we add it a query string, and to the URL instead.

5-curl-get.php
 "Good Boy",
  "cate" => "Evil"
];
$query = "?";
foreach ($data as $k=>$v) {
  $query .= urlencode($k) . "=" . urlencode($v) . "&";
}
$query = substr($query, 0, -1);

// (2B) SET OPTIONS
curl_setopt_array($curl, [
  CURLOPT_URL => "https://whatever.com/xyz.php" . $query,
  CURLOPT_RETURNTRANSFER => true // Optional, if you need the remote server response
]);

// (3) EXECUTE CURL
$result = curl_exec($curl);

// (3A) ERROR
if ($result === false) {
  echo curl_error($curl); // Error message
  echo curl_errno($curl); // Error code
}
// (3B) OK
else {
  echo $result;
}

// (4) CLOSE CURL CONNECTION
curl_close($curl);
?>

HTTP AUTH

Yes, we can access an HTTP password protected site too.

6-curl-auth.php
 "https://whatever.com/xyz.php",
  CURLOPT_HTTPAUTH => CURLAUTH_ANY,
  CURLOPT_USERPWD  => "USERNAME:PASSWORD",
  CURLOPT_RETURNTRANSFER => true
]);

// (3) EXECUTE CURL
$result = curl_exec($curl);

// (3A) ERROR
if ($result === false) {
  echo curl_error($curl); // Error message
  echo curl_errno($curl); // Error code
}
// (3B) OK
else {
  echo $result;
}

// (4) CLOSE CURL CONNECTION
curl_close($curl);
?>

COOKIES

Need to track your login and stuff? Cookies are supported as well.

7-curl-cookie.php
 "https://whatever.com/xyz.php",
  // Where to write the cookie to
  CURLOPT_COOKIEFILE => $cookie,
  // Where to read the cookie from
  CURLOPT_COOKIEJAR => $cookie,
  CURLOPT_RETURNTRANSFER => true
]);

// (3) EXECUTE CURL
$result = curl_exec($curl);

// (3A) ERROR
if ($result === false) {
  echo curl_error($curl); // Error message
  echo curl_errno($curl); // Error code
}
// (3B) OK
else {
  echo $result;
}

// (4) CLOSE CURL CONNECTION
curl_close($curl);
?>

EXTRA
USEFUL BITS

That’s all for this project, and here is a small section on some extras that may be useful to you.

REFERENCE

cURL is a lot more capable than just fetching from HTTP, we can also connect FTP servers, and even do Telnet. Please do check out the official Php Curl manual for more.

JSON

For the beginners – What is JSON? Read my other guide.

JSON in PHP and Javascript For Beginners – The Comprehensive Guide

CHEAT SHEET

PHP cURL Basics (click to enlarge)

EXTRA
DOWNLOAD

Finally, here is the download link as promised.

SOURCE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
 

CLOSING
WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand cURL, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

The post How to Use PHP cURL (Examples Included) appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

How to Use PHP cURL (Examples Included)

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×