In depth analysis of the reason why the file_get_contents function failed to fetch content

  • 2020-06-19 09:59:28
  • OfStack

Using file_get_contents to grab the page content was unsuccessful, possibly because some host service providers turned php's allow_url_fopen option off, but could not 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 using 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;
?>

Related articles: