Mastering PHP curl_setopt: Set HTTP Options Like a Pro

This guide explains the PHP curl_setopt function, covering its syntax, parameters, return value, and a complete example that demonstrates how to configure and execute a GET request with cURL, handle errors, and close the session.

php Courses
php Courses
php Courses
Mastering PHP curl_setopt: Set HTTP Options Like a Pro

cURL is a powerful PHP extension for sending and receiving HTTP requests. The curl_setopt() function is essential for setting options on a cURL session.

Syntax

bool curl_setopt ( resource $ch , int $option , mixed $value )

Parameter explanation

$ch: cURL handle created by curl_init().

$option: the cURL option to set.

$value: the value for the option.

Return value

The function returns a boolean indicating success.

Example

The following example uses curl_setopt() to send a GET request to a URL and retrieve the response.

// Initialize cURL session
$ch = curl_init();

// Set URL to request
curl_setopt($ch, CURLOPT_URL, "https://api.example.com/data");

// Set request method to GET
curl_setopt($ch, CURLOPT_HTTPGET, true);

// Return response as string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Set timeout
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

// Execute request
$response = curl_exec($ch);

if ($response === FALSE) {
    echo "Request failed: " . curl_error($ch);
} else {
    echo $response;
}

// Close session
curl_close($ch);

Explanation

The example first creates a cURL handle with curl_init(), then sets options such as CURLOPT_URL, CURLOPT_HTTPGET, CURLOPT_RETURNTRANSFER, and CURLOPT_TIMEOUT. curl_exec() executes the request, and errors can be retrieved with curl_error(). Finally, curl_close() closes the session.

Summary

The curl_setopt() function is crucial for configuring a cURL session, allowing you to set URL, request method, timeout, and other options to send and receive HTTP requests in PHP.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPcURLHTTP requestphp-tutorialcurl_setopt
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.