Drill down to the file_get_contents and curl functions

  • 2020-06-19 09:56:23
  • OfStack

Some hosting providers have turned off php's allow_url_fopen option, but can't directly use file_get_contents to get the content of remote web pages. That is, you can use another function, curl.
Here are two different ways of writing the same function, file_get_contents and curl
Example of the file_get_contents function:

< ?php
$file_contents = file_get_contents('https://www.ofstack.com');
echo $file_contents;
?>

Use examples of curl functions instead:

< ?php
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, 'https://www.ofstack.com');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
echo $file_contents;
?>

Using the function_exists function to determine if php supports 1 function, you can easily write the following function

< ?php
function vita_get_url_content($url) {
if(function_exists('file_get_contents')) {
$file_contents = file_get_contents($url);
} else {
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
}
return $file_contents;
}
?>

In fact, the above function is still questionable, if your host service has turned off both file_get_contents and curl, the above function will have an error.

Related articles: