How To Make HTTP Requests in PHP - curl() Function

cURL means client URL. It allows you to connect with other URLs and use their responses in your code.

Use curl in PHP is very simple process:

  1. Initialize a curl session
  2. Set various options for the session
  3. Execute and fetch data from server or send data to server
  4. Close the session
<?php
// Initialize curl session
$ch = curl_init();

// Set options
curl_setopt($ch, CURLOPT_URL, "http://www.google.com/search?q=curl");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);

// Execute
$result = curl_exec($ch);

// Close curl session
curl_close($ch);

// Output result
echo $result;
?>

Setting URL option with the $url variable passed into the function:

curl_setopt($ch, CURLOPT_URL, $url);

Setting option to return the webpage data:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

 

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive