The solution for file_get_contents returns null or the function is not available

  • 2020-06-19 09:54:58
  • OfStack

If you use file_get_contents to get remote file contents that return empty or indicate that the function is unavailable, maybe this article will help you!
allow_url_fopen must be enabled using file_get_contents and fopen. Edit php.ini, set allow_url_fopen = On, allow_url_fopen close fopen and file_get_contents cannot open remote files. If you are using a virtual host, consider using the curl function instead.
Examples of using the curl function:

$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);

Use the function_exists function to determine whether php supports file_get_contents, or use the curl function instead.
PS
1. If your hosting service is shutting down curl, switch to another host.
Setting allow_url_fopen to off does not mean that your host does not support the file_get_content function. You just can't open a remote file. function_exists(' file_get_contents') returns true. So the "Solution to the unavailability of file_get_contents" circulating on the Internet still doesn't solve the problem.
Error code:

if (function_exists( ' file_get_contents')) {
$file_contents = @file_get_contents($url);
}else{
$ch = curl_init();
$timeout = 30;
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);
}

Should be changed to:

if (function_exists( ' file_get_contents')) {// Judge whether to support file_get_contents
$file_contents = @file_get_contents($url);
}
if ($file_contents ==  " ) {// judge $file_contents Whether is empty 
$ch = curl_init();
$timeout = 30;
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);
}

Final code:

function file_get_content($url) {
if (function_exists( ' file_get_contents')) {
$file_contents = @file_get_contents($url);
}
if ($file_contents ==  " ) {
$ch = curl_init();
$timeout = 30;
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;
}

Usage:
echo file_get_content (" https: / / www. ofstack. com ');

Related articles: