Using curl_exec() in PHP to Retrieve Web Content
This article explains how the PHP cURL library, especially the curl_exec() function, can be used to initialize a session, set options, execute HTTP requests, handle errors, and retrieve remote page content efficiently.
cURL is a powerful PHP library for handling URL requests, offering many functions to send and receive data and interact with remote servers; among them, curl_exec() is one of the most commonly used functions.
The curl_exec() function executes an already initialized cURL session, sending the request and obtaining the server's response. Before calling it, you must initialize the session with curl_init() and configure options using functions such as curl_setopt() .
Below is an example that uses curl_exec() to fetch a web page:
// Initialize a cURL session
$curl_handle = curl_init();
// Set cURL options
curl_setopt($curl_handle, CURLOPT_URL, "http://www.example.com"); // Set URL
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true); // Return result as a string
// Execute cURL session
$response = curl_exec($curl_handle);
// Check for errors
if (curl_errno($curl_handle)) {
// Output error message
echo "cURL Error: " . curl_error($curl_handle);
}
// Close cURL session
curl_close($curl_handle);
// Output the fetched page content
echo $response;In the example, curl_init() creates a cURL session and assigns it to $curl_handle . Then curl_setopt() sets two options: CURLOPT_URL to specify the request URL and CURLOPT_RETURNTRANSFER set to true so the result is returned to a variable instead of being directly output.
Next, curl_exec() runs the session and stores the returned data in $response . If an error occurs during execution, you can retrieve the error code with curl_errno() and the error message with curl_error() for handling.
Finally, curl_close() closes the cURL session, and the script echoes the fetched page content.
Note that because curl_exec() performs network requests, its execution time may be long, especially when handling large data. To prevent script timeouts, you can set an appropriate execution time limit using set_time_limit() .
In summary, curl_exec() is a crucial function for making network requests with PHP's cURL library; it executes an initialized session and retrieves the server response. Before using it, you must initialize the session, set the required options, and close the session afterward. In practice, curl_exec() is commonly used to fetch remote data, call API endpoints, and similar scenarios.
Hopefully this introduction helps you understand and use curl_exec() more effectively, enabling you to handle URL requests flexibly and develop more powerful PHP applications.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.