Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Web and Security

PHP cURL functions

Reference for PHP's cURL extension: curl_init(), curl_setopt(), curl_exec() and curl_multi_*, to send GET and POST requests, set headers, timeouts and handle errors.

The cURL extension lets a PHP script act as an HTTP client: call a JSON API, post a form, upload a file or download a page. You create a handle with curl_init(), set options with curl_setopt() or curl_setopt_array(), run it with curl_exec(), and read details with curl_getinfo() and curl_error().

Since PHP 8.0 a handle is a CurlHandle object, and it is closed automatically when it goes out of scope, so curl_close() is no longer needed. The examples that contact a real server are read-only here, because the runner has no network. The live examples show what works offline: building options and handling failures.

PHP
$ch = curl_init('https://api.example.com/items');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$body = curl_exec($ch);

Try it

Read-only: a GET request for JSON and a POST with a JSON body.

PHP
<?php
function request(string $method, string $url, ?array $json = null): array
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,        // return the body instead of printing it
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 3,
        CURLOPT_HTTPHEADER => ['Accept: application/json', 'Content-Type: application/json'],
        CURLOPT_POSTFIELDS => $json === null ? null : json_encode($json),
    ]);

    $body = curl_exec($ch);
    if ($body === false) {
        throw new RuntimeException('cURL error ' . curl_errno($ch) . ': ' . curl_error($ch));
    }

    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    return [$status, json_decode($body, true, 512, JSON_THROW_ON_ERROR)];
}

[$status, $data] = request('GET', 'https://api.example.com/items/1');
[$status, $created] = request('POST', 'https://api.example.com/items', ['name' => 'Pen']);
PHP Handling a failed connection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Building a POST body and inspecting options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
curl_init(?string $url = null): CurlHandle|false
curl_setopt(CurlHandle $handle, int $option, mixed $value): bool
curl_setopt_array(CurlHandle $handle, array $options): bool
curl_exec(CurlHandle $handle): string|bool
curl_getinfo(CurlHandle $handle, ?int $option = null): mixed
curl_errno(CurlHandle $handle): int
curl_error(CurlHandle $handle): string

Frequently used options:

Option Meaning
CURLOPT_RETURNTRANSFER true makes curl_exec() return the body instead of printing it.
CURLOPT_POST, CURLOPT_POSTFIELDS Send a POST with a string (raw) or an array (multipart).
CURLOPT_CUSTOMREQUEST Use PUT, PATCH, DELETE.
CURLOPT_HTTPHEADER A list of header lines such as 'Authorization: Bearer ...'.
CURLOPT_TIMEOUT, CURLOPT_CONNECTTIMEOUT Total and connect time limits in seconds.
CURLOPT_FOLLOWLOCATION, CURLOPT_MAXREDIRS Follow redirects, up to a limit.
CURLOPT_SSL_VERIFYPEER Keep true (default).
CURLOPT_USERAGENT, CURLOPT_ENCODING Set the user agent; '' enables compressed responses.

Usage notes

  • Check false and the HTTP status separately. curl_exec() returns false only for transport failures (DNS, connect, timeout). A 404 or 500 is a successful transfer; read CURLINFO_RESPONSE_CODE yourself.
  • Always set timeouts. The defaults are very generous, and a slow API can hold your PHP workers.
  • Never turn off certificate checks (CURLOPT_SSL_VERIFYPEER => false) to "fix" an error. Install the CA bundle instead (curl.cainfo in php.ini).
  • Reuse handles for several requests to the same host to keep connections alive; curl_reset() clears options.
  • Parallel requests: the curl_multi_* functions run several handles at once.
  • Do not fetch user-supplied URLs blindly: an attacker can aim your server at internal addresses (SSRF). Allow-list hosts and schemes.
  • Alternatives: file_get_contents() with a stream context works for simple GETs; Guzzle or Symfony HttpClient (via Composer) wrap cURL with a friendlier API.
  • The extension is optional; check extension_loaded('curl').