Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

curl_setopt

Sets an option of a cURL request.

Syntax

curl_setopt(CurlHandle $handle, int $option, mixed $value): bool

Parameters

ParameterTypeDescription
$handleCurlHandleA request created with `curl_init()`.
$optionintThe option — a `CURLOPT_…` constant.
$valuemixedThe option value.

Return value

bool`true` on success.

Examples

Sending JSON with POST:

<?php
 
// create-order.php
 
$curl = curl_init('https://api.example.com/orders');
 
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 5,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode(['product_id' => 42]),
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
]);
 
$response = curl_exec($curl);

Notes

Several options are easier to set with one curl_setopt_array() call. Always set CURLOPT_TIMEOUT.

See also

Related recipes

In the tutorial

  • Calling other sites — How to call someone else's API from PHP — file_get_contents, the cURL extension, sending JSON, headers, the response code and error handling.

Thanks for reading!

Donate to the site — we work hard for you.