Replace file_get_contents() with cURL?

2019-05-23 06:40发布

问题:

I don't want to use this function because to it's unavailability on some servers for security reasons, how can i replace file_get_contents() with cURL ?

The line below is causing me a problem on my server :

$response = file_get_contents('http://images.google.com/images?hl=en&q=' . urlencode ($query) . '&imgsz=' . $size . '&imgtype=' . $type . '&start=' . (($page - 1) * 21));

How can i replace the line with another one that uses curl so it will work on every server ?

回答1:

here is a clean function you can use

$response = get_data('http://images.google.com/images?hl=en&q=' . urlencode ($query) . '&imgsz=' . $size . '&imgtype=' . $type . '&start=' . (($page - 1) * 21));

function get_data($url)
{
  $ch = curl_init();
  $timeout = 5;
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
  $data = curl_exec($ch);
  curl_close($ch);
  return $data;
}