All Courses
Scraping

Practical PHP cURL Syntax Examples

When using the previous cURL command syntax, you can do both send and receive data from the URLs of your choice. Here, we’ll show you cURL syntax to both GET and POST in PHP, as well as how to handle potential errors and responses.

cURL GET Syntax

A GET request retrieves data from a specified URL.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://jsonplaceholder.typicode.com/posts/1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
} else {
    $data = json_decode($response, true); // Decode JSON response
    print_r($data);
}

curl_close($ch);

cURL POST Syntax

A POST request sends data to the server, often used for submitting forms or JSON data.

$ch = curl_init();

$data = json_encode([
    'title' => 'foo',
    'body' => 'bar',
    'userId' => 1,
]);

curl_setopt($ch, CURLOPT_URL, "https://jsonplaceholder.typicode.com/posts");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Set headers for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data)
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
} else {
    $responseData = json_decode($response, true);
    print_r($responseData);
}

curl_close($ch);

cURL Syntax for Handling Errors and Debugging:

You can use curl_errno() and curl_error() to check and display errors.

Enable verbose output for debugging:

curl_setopt($ch, CURLOPT_VERBOSE, true);

For HTTPS requests, consider setting:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Note: Disabling SSL verification can expose you to security risks, so use it only for testing purposes.

By understanding the basics of cURL and how to use it effectively, you can perform robust HTTP requests for web scraping and other applications.

Join Our Community!

Our community is here to support your growth, so why wait? Join now and let’s build together!

ArrowArrow
Try Rayobyte proxies for all your scraping needs
Explore Now

See What Makes Rayobyte Special For Yourself!