PHP HTTP Client: Making Requests Correctly from A to Z

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why Do You Need an HTTP Client in PHP?

\n\n

Modern web development is unthinkable without interaction with external services. Whether it's sending data to a third-party API, fetching currency exchange rates, or integrating with a payment gateway — every PHP developer faces the need to make HTTP requests. Creating a reliable HTTP client in PHP is a core competency that allows your application to communicate with the rest of the world.

\n\n

In this article, we will cover two main approaches: using the built-in cURL extension and the popular Guzzle library. You will learn how to properly send GET, POST, PUT, and DELETE requests, handle errors, and work with headers. This material will be useful for both beginners and experienced developers looking to systematize their knowledge.

\n\n

1. Basics of an HTTP Client in PHP: Working with cURL

\n\n

1.1. What is cURL and Why is it Important

\n\n

cURL (Client URL Library) is a powerful PHP extension that allows you to interact with various servers using HTTP, HTTPS, FTP, and other protocols. It comes bundled with PHP by default but sometimes requires separate activation in php.ini. cURL gives you full control over the request: you can set any method, headers, request body, and timeouts.

\n\n

1.2. Simple GET Request with cURL

\n\n

Let's start with the most common scenario — fetching data from a server. Consider an example request to the public JSONPlaceholder API:

\n\n
<?php\n// Initialize cURL session\n$ch = curl_init('https://jsonplaceholder.typicode.com/posts/1');\n\n// Set options\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\ncurl_setopt($ch, CURLOPT_HTTPGET, true);\ncurl_setopt($ch, CURLOPT_TIMEOUT, 30);\n\n// Execute request\n$response = curl_exec($ch);\n$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);\n\n// Check for errors\nif (curl_errno($ch)) {\n    echo 'cURL error: ' . curl_error($ch);\n} else {\n    echo "HTTP code: $httpCode\\n";\n    $data = json_decode($response, true);\n    print_r($data);\n}\n\n// Close session\ncurl_close($ch);\n?>
\n\n

Note: we always check the response code and for errors. CURLOPT_RETURNTRANSFER ensures the result is returned to a variable rather than output directly.

\n\n

1.3. Sending a POST Request with Data

\n\n

To send data to a server (for example, when creating a new record), use POST. Data can be passed as an array or a JSON string:

\n\n
<?php\n$ch = curl_init('https://jsonplaceholder.typicode.com/posts');\n\n$postData = [\n    'title' => 'New post',\n    'body' => 'Post content',\n    'userId' => 1\n];\n\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_POST => true,\n    CURLOPT_POSTFIELDS => json_encode($postData), // JSON\n    CURLOPT_HTTPHEADER => [\n        'Content-Type: application/json',\n        'Accept: application/json'\n    ],\n    CURLOPT_TIMEOUT => 30\n]);\n\n$response = curl_exec($ch);\n$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);\ncurl_close($ch);\n\necho "HTTP code: $httpCode\\n";\necho $response;\n?>
\n\n

Key point: if you pass an array to CURLOPT_POSTFIELDS, PHP will automatically encode it as application/x-www-form-urlencoded. For JSON, you need to use json_encode() and explicitly set the Content-Type header.

\n\n

1.4. PUT and DELETE Requests

\n\n

For updating and deleting resources, the PUT and DELETE methods are used. In cURL, they are set via the CURLOPT_CUSTOMREQUEST option:

\n\n
<?php\n// PUT request (update)\n$ch = curl_init('https://jsonplaceholder.typicode.com/posts/1');\n$updateData = ['title' => 'Updated title'];\n\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => 'PUT',\n    CURLOPT_POSTFIELDS => json_encode($updateData),\n    CURLOPT_HTTPHEADER =>                

Blogs

Book Recommendations