cURL requests
The curl library is how PHP talks to another server: the extension builds a handle, sets options on it, and sends one HTTPS request. The examples below run on this page, and each one prints what the call really returned here.
Init a handle
Every request starts with a handle that stores the target and the settings. Create it with the URL, then tune behavior before sending.
Return transfer keeps the answer as a string, while a timeout stops slow servers from blocking the script.
<?php $ch = curl_init("https://example.com"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); echo get_debug_type($ch), PHP_EOL; echo parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL), PHP_URL_HOST), PHP_EOL;
php init.php
CurlHandle
example.com
The handle is a CurlHandle object and it already knows its host, so the URL and the two options are in place before any byte moves.
Set options
Options control headers, redirects, and methods without changing the main flow. Set them one by one after init for clarity.
Keep redirect limits small and send explicit Accept headers when asking for JSON data.
<?php $ch = curl_init("https://example.com"); var_dump(curl_setopt($ch, CURLOPT_HTTPHEADER, ["Accept: application/json"])); var_dump(curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true)); var_dump(curl_setopt($ch, CURLOPT_MAXREDIRS, 3));
php options.php
bool(true)
bool(true)
bool(true)
Each call answers true, which is how PHP tells you that the option name and the value were accepted. A misspelled constant or a value of the wrong type gives false or a ValueError.
Exec and close
Exec sends the request and returns the body. Closing the handle was once the last step, but PHP 8.0 made
curl_close() a no-op and PHP 8.5 deprecates it, so the handle is simply left to go out of
scope and no call is needed.
Short previews during debugging help confirm shape before parsing the full payload.
<?php file_put_contents(__DIR__ . "/answer.json", "{\"ok\":true,\"items\":[1,2,3]}"); $ch = curl_init("file://" . __DIR__ . "/answer.json"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); echo substr((string) $response, 0, 200), PHP_EOL; var_dump(curl_errno($ch));
php exec.php
{"ok":true,"items":[1,2,3]}
int(0)
The transfer below reads a local file through the file handler, so it prints the same body on a machine without a network; the same call with an https URL returns the page body instead. Error code zero means the transfer finished, and the preview cuts the body before it fills the screen.
Handle errors
Network calls can fail, so every exec needs a check. A false result means the error helpers hold the reason and the code.
Log both parts, then retry or show a friendly message; the handle needs no close call.
<?php $ch = curl_init("http://127.0.0.1:1/"); curl_setopt($ch, CURLOPT_TIMEOUT, 2); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); if ($response === false) { echo curl_error($ch), PHP_EOL; echo curl_errno($ch), PHP_EOL; }
php errors.php
Failed to connect to 127.0.0.1:1 after 0 ms: Could not connect to server
7
Port 1 answers nowhere, which makes the refusal repeatable on any machine. Code 7 is CURLE_COULDNT_CONNECT; a timeout, a bad certificate and a DNS miss each have their own number, so a log line with both parts names the failure without a guess.
Exercises
- Point the init example at a path of your own and print its host and its path.
- Turn CURLOPT_RETURNTRANSFER off in the exec example and describe what the output becomes.
- Ask a closed port with a one second timeout and print the error message.
- Print curl_getinfo($ch, CURLINFO_RESPONSE_CODE) after a failed request and explain the zero.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
curl_init()return?Answer
A
CurlHandleobjectSince PHP 8.0 the handle is an object of the class
CurlHandle, and every option and transfer call takes it. -
What does
CURLOPT_RETURNTRANSFERchange?Answer
It makes
curl_exec()return the body instead of printing itWith the option on, the body comes back as the return value; without it,
curl_exec()prints the body and returns true. -
Which pair reports why a transfer failed?
Answer
curl_errno()andcurl_error()The number names the kind of failure and the string carries the message, and both belong in the log.
-
What does
CURLOPT_FOLLOWLOCATIONdo?Answer
It follows the Location header of a redirect
The client makes the second request for you, up to the limit set with
CURLOPT_MAXREDIRS. -
What does this program print?
<?php $ch = curl_init("https://example.com/page"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); echo parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL), PHP_URL_HOST);Answer
example.com
The handle already knows the URL, and
parse_url()withPHP_URL_HOSTkeeps only the host part. -
What does this program print?
<?php $ch = curl_init("https://example.com"); var_dump(curl_setopt($ch, CURLOPT_HTTPHEADER, ["Accept: application/json"])); var_dump(curl_setopt($ch, CURLOPT_MAXREDIRS, 3));Answer
bool(true) / bool(true)
Both option calls are accepted, so each one returns true and prints as
bool(true). -
What does this program print?
<?php file_put_contents(__DIR__ . "/note.txt", "hi"); $ch = curl_init("file://" . __DIR__ . "/note.txt"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $body = curl_exec($ch); echo substr((string) $body, 0, 10);Answer
hiReturn transfer hands the file contents back, and the preview prints the two bytes of the file.
-
What does this program print?
<?php $ch = curl_init("http://127.0.0.1:1/"); curl_setopt($ch, CURLOPT_TIMEOUT, 2); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $body = curl_exec($ch); if ($body === false) { echo curl_errno($ch); }Answer
7
Nothing listens on port 1, so the connect fails with
CURLE_COULDNT_CONNECT, whose number is 7. -
Why does the exec example not call
curl_close()?Answer
Because the call is deprecated in PHP 8.5 and has done nothing since PHP 8.0
Closing stopped freeing anything in PHP 8.0, and PHP 8.5 deprecates the function, so the handle just goes out of scope.
-
The response of a failed transfer is not checked and is cast with
(string) $response. What does a preview print?Answer
An empty string, with the error hidden
falsecasts to an empty string, so the page looks like an empty answer and the real reason is lost.
The examples call parse_url() and substr(). The programs on this page were run with PHP 8.5.13 (php -v) and its curl extension, with the commands shown above.
Article author: Arthur Isaev