<?php // Initialize CURL $curl = curl_init(); // Set the target URL $url = "https://api.example.com/data"; // Set CURL options curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Execute request $response = curl_exec($curl); // Close CURL session curl_close($curl); // Output result if ($response) { echo $response; } else { echo "Request failed"; } ?>
In this example, setting CURLOPT_RETURNTRANSFER to true ensures the response is returned as a string rather than being directly output.
<?php // Initialize CURL $curl = curl_init(); // Set the URL $url = "https://api.example.com/data"; // POST data $data = array( 'username' => 'user123', 'password' => 'pass123' ); // Configure CURL options curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Execute request $response = curl_exec($curl); // Close CURL curl_close($curl); // Handle response if ($response) { echo $response; } else { echo "Request failed"; } ?>
In this code, http_build_query() is used to convert the POST data array into a URL-encoded string for transmission.
<?php // Initialize CURL $curl = curl_init(); // Request URL $url = "https://api.example.com/data"; // Configure CURL options curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 10); // Set timeout to 10 seconds // Execute request $response = curl_exec($curl); // Check for errors if (curl_errno($curl)) { $error_msg = curl_error($curl); echo "An error occurred: " . $error_msg; } else { // Output response if ($response) { echo $response; } else { echo "Request failed"; } } // Close session curl_close($curl); ?>
By setting CURLOPT_TIMEOUT, you define the maximum time CURL should wait for a response. Additionally, curl_errno() and curl_error() help detect and display errors that occurred during the request.