PHP cURL Tutorial: Using cURL to Make HTTP Requests

cURL is a powerful PHP extension that allows you to communicate with different servers using various protocols, including HTTP, HTTPS, FTP, and more.

It is widely used for making HTTP requests to interact with APIs, download files, and perform other network-related operations.

Basic cURL Workflow

  1. Initialize a cURL session: curl_init()
  2. Set options for the cURL transfer: curl_setopt()
  3. Execute the cURL session: curl_exec()
  4. Close the cURL session: curl_close()

Example: Fetching a Web Page

Here is a basic example that demonstrates how to fetch the contents of a web page and save it to a file:

<?php
// Initialize a cURL session
$ch = curl_init("http://www.example.com/");

// Open a file to write the content
$fp = fopen("example_homepage.txt", "w");

// Set cURL options
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

// Execute the cURL session
curl_exec($ch);

// Check for errors
if (curl_error($ch)) {
    fwrite($fp, curl_error($ch));
}

// Close the cURL session and file
curl_close($ch);
fclose($fp);
?>

 

Example: Making a POST Request

POST requests are often used to send data to a server. Here’s how to make a POST request with cURL:

<?php
$url = 'http://demo.tld/post';
$fields = ['name' => 'John Doe', 'occupation' => 'gardener'];

// Initialize a cURL session
$ch = curl_init($url);

// Set cURL options
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the cURL session and fetch the response
$response = curl_exec($ch);

// Close the cURL session
curl_close($ch);

// Output the response
echo $response;
?>

 

Example: Sending JSON Data

Sometimes, APIs require JSON formatted data. You can use json_encode() to prepare your data:

<?php
$url = 'http://httpbin.org/post';
$data = json_encode(['name' => 'John Doe', 'occupation' => 'gardener']);

// Initialize a cURL session
$ch = curl_init($url);

// Set cURL options
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the cURL session and fetch the response
$response = curl_exec($ch);

// Close the cURL session
curl_close($ch);

// Output the response
echo $response;
?>

 

Handling Multiple Requests

cURL also supports handling multiple requests simultaneously using curl_multi_init(). This is useful for fetching multiple resources concurrently:

<?php
$urls = [
    "http://webcode.me",
    "https://example.com",
    "http://httpbin.org",
    "https://www.perl.org"
];

$mh = curl_multi_init();
$chs = [];

foreach ($urls as $url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_multi_add_handle($mh, $ch);
    $chs[] = $ch;
}

$running = null;
do {
    curl_multi_exec($mh, $running);
} while ($running);

foreach ($chs as $ch) {
    echo curl_multi_getcontent($ch);
    curl_multi_remove_handle($mh, $ch);
}

curl_multi_close($mh);
?>

 

Debugging cURL Requests

For debugging, you can use curl_getinfo() to get information about the request and curl_error() to print error messages:

<?php
$url = "http://www.example.com/";
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    $info = curl_getinfo($ch);
    print_r($info);
}

curl_close($ch);
?>

 

The cURL extension in PHP is a versatile tool for making HTTP requests. By mastering cURL, you can interact with web services, download files, and perform various network operations efficiently.

 

For more detailed information, you can refer to the PHP Manual on cURL.

 

Author

Ratings

There are no comments available yet.

Here you can write a comment


Please enter at least 10 characters.
Loading... Please wait.
* Pflichtangabe

Related topics

Text-Counter mit IP-Sperre ( Cookies oder Datei)

In diesem Tutorial möchte ich erklären wir man auf 2 arten einen Counter Programmieren kann,nebenbei werden ein paar Datei Funktionen erklärt! ...

support1@

Autor : support1@
Category: PHP-Tutorials

Apache und Windows/XP

Beschreibung zum einrichten des Apache2 unter Windows 2000/XP ...

info225@

Autor : info225@
Category: Linux & Server Tutorials

Publish a tutorial

Share your knowledge with other developers worldwide

Share your knowledge with other developers worldwide

You are a professional in your field and want to share your knowledge, then sign up now and share it with our PHP community

learn more

Publish a tutorial