HTTP Client in PHP: Making Requests the Right Way

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



In modern PHP web development, almost no project can do without sending HTTP requests. Whether it's integration with an external API, fetching data from a remote server, submitting forms, or checking resource availability — the ability to work competently with HTTP clients is a mandatory skill for any PHP developer.



In this article, we will break down three main ways to create an HTTP client in PHP: the built-in functions file_get_contents and cURL, as well as the popular library Guzzle. You will learn how to properly send GET and POST requests, handle errors, work with headers and timeouts. The material will be useful for both beginners and experienced developers looking to systematize their knowledge.



1. The Simplest Way: file_get_contents



The fastest way to send a GET request in PHP is to use the file_get_contents() function with a URL. However, this method has serious limitations.



Simple GET Request



<?php$url = 'https://api.example.com/users';$response = file_get_contents($url);if ($response === false) {    echo 'Error fetching data';} else {    echo $response;}?>


Adding Headers via Stream Context



To add headers or change the request method, you need to use stream_context_create():



<?php$url = 'https://api.example.com/data';$options = [    'http' => [        'method' => 'GET',        'header' => "Accept: application/json\\r" .                     "Authorization: Bearer your-token\\r"    ]];$context = stream_context_create($options);$response = file_get_contents($url, false, $context);if ($response === false) {    echo 'Request error';} else {    $data = json_decode($response, true);    print_r($data);}?>


POST Request via file_get_contents



<?php$url = 'https://api.example.com/create';$data = ['name' => 'John', 'email' => 'john@example.com'];$options = [    'http' => [        'method' => 'POST',        'header' => "Content-Type: application/json\\r",        'content' => json_encode($data)    ]];$context = stream_context_create($options);$response = file_get_contents($url, false, $context);?>


Disadvantages of file_get_contents:

  • No timeout support (waits indefinitely by default)
  • Difficult to handle connection errors
  • No ability to download files in parts
  • Poorly suited for complex scenarios


2. A Powerful Tool: cURL



cURL is the standard tool for working with HTTP in PHP. It provides full control over requests and supports almost all protocol capabilities.



Basic Initialization and GET Request



<?php$ch = curl_init('https://api.example.com/users');curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);$response = curl_exec($ch);if (curl_errno($ch)) {    echo 'cURL error: ' . curl_error($ch);} else {    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);    echo "HTTP code: $httpCode";    echo $response;}curl_close($ch);?>


POST Request with Data



<?php$ch = curl_init('https://api.example.com/users');curl_setopt_array($ch, [    CURLOPT_RETURNTRANSFER => true,    CURLOPT_POST => true,    CURLOPT_POSTFIELDS => json_encode([        'name' => 'Jane Doe',        'email' => 'jane@example.com'    ]),    CURLOPT_HTTPHEADER => [        'Content-Type: application/json',        'Accept: application/json'    ],    CURLOPT_TIMEOUT => 30,    CURLOPT_CONNECTTIMEOUT => 10]);$response = curl_exec($ch);$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);curl_close($ch);                

Blogs

Book Recommendations