How can I handle the warning of file_get_contents() function in PHP?
PhpFunctionExceptionWarningsFile Get-ContentsPhp Problem Overview
I wrote a PHP code like this
$site="http://www.google.com";
$content = file_get_content($site);
echo $content;
But when I remove "http://" from $site
I get the following warning:
> Warning: > file_get_contents(www.google.com) > [function.file-get-contents]: failed > to open stream:
I tried try
and catch
but it didn't work.
Php Solutions
Solution 1 - Php
Step 1: check the return code: if($content === FALSE) { // handle error here... }
Step 2: suppress the warning by putting an error control operator (i.e. @
) in front of the call to file_get_contents():
$content = @file_get_contents($site);
Solution 2 - Php
You can also set your error handler as an anonymous function that calls an Exception and use a try / catch on that exception.
set_error_handler(
function ($severity, $message, $file, $line) {
throw new ErrorException($message, $severity, $severity, $file, $line);
}
);
try {
file_get_contents('www.google.com');
}
catch (Exception $e) {
echo $e->getMessage();
}
restore_error_handler();
Seems like a lot of code to catch one little error, but if you're using exceptions throughout your app, you would only need to do this once, way at the top (in an included config file, for instance), and it will convert all your errors to Exceptions throughout.
Solution 3 - Php
My favorite way to do this is fairly simple:
if (($data = @file_get_contents("http://www.google.com")) === false) {
$error = error_get_last();
echo "HTTP request failed. Error was: " . $error['message'];
} else {
echo "Everything went better than expected";
}
I found this after experimenting with the try/catch
from @enobrev above, but this allows for less lengthy (and IMO, more readable) code. We simply use error_get_last
to get the text of the last error, and file_get_contents
returns false on failure, so a simple "if" can catch that.
Solution 4 - Php
You can prepend an @:
$content = @file_get_contents($site);
This will supress any warning - use sparingly!. See http://www.php.net/@">Error Control Operators
Edit: When you remove the 'http://' you're no longer looking for a web page, but a file on your disk called "www.google....."
Solution 5 - Php
One alternative is to suppress the error and also throw an exception which you can catch later. This is especially useful if there are multiple calls to file_get_contents() in your code, since you don't need to suppress and handle all of them manually. Instead, several calls can be made to this function in a single try/catch block.
// Returns the contents of a file
function file_contents($path) {
$str = @file_get_contents($path);
if ($str === FALSE) {
throw new Exception("Cannot access '$path' to read contents.");
} else {
return $str;
}
}
// Example
try {
file_contents("a");
file_contents("b");
file_contents("c");
} catch (Exception $e) {
// Deal with it.
echo "Error: " , $e->getMessage();
}
Solution 6 - Php
function custom_file_get_contents($url) {
return file_get_contents(
$url,
false,
stream_context_create(
array(
'http' => array(
'ignore_errors' => true
)
)
)
);
}
$content=FALSE;
if($content=custom_file_get_contents($url)) {
//play with the result
} else {
//handle the error
}
Solution 7 - Php
Here's how I did it... No need for try-catch block... The best solution is always the simplest... Enjoy!
$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) {
echo "SUCCESS";
} else {
echo "FAILED";
}
Solution 8 - Php
Here's how I handle that:
$this->response_body = @file_get_contents($this->url, false, $context);
if ($this->response_body === false) {
$error = error_get_last();
$error = explode(': ', $error['message']);
$error = trim($error[2]) . PHP_EOL;
fprintf(STDERR, 'Error: '. $error);
die();
}
Solution 9 - Php
The best thing would be to set your own error and exception handlers which will do something usefull like logging it in a file or emailing critical ones. http://www.php.net/set_error_handler
Solution 10 - Php
Since PHP 4 use error_reporting():
$site="http://www.google.com";
$old_error_reporting = error_reporting(E_ALL ^ E_WARNING);
$content = file_get_content($site);
error_reporting($old_error_reporting);
if ($content === FALSE) {
echo "Error getting '$site'";
} else {
echo $content;
}
Solution 11 - Php
something like this:
public function get($curl,$options){
$context = stream_context_create($options);
$file = @file_get_contents($curl, false, $context);
$str1=$str2=$status=null;
sscanf($http_response_header[0] ,'%s %d %s', $str1,$status, $str2);
if($status==200)
return $file
else
throw new \Exception($http_response_header[0]);
}
Solution 12 - Php
You could use this script
$url = @file_get_contents("http://www.itreb.info");
if ($url) {
// if url is true execute this
echo $url;
} else {
// if not exceute this
echo "connection error";
}
Solution 13 - Php
You should use file_exists() function before to use file_get_contents(). With this way you'll avoid the php warning.
$file = "path/to/file";
if(file_exists($file)){
$content = file_get_contents($file);
}
Solution 14 - Php
Simplest way to do this is just prepend an @ before file_get_contents, i. e.:
$content = @file_get_contents($site);
Solution 15 - Php
I was resolve all problem, it's work all links
public function getTitle($url)
{
try {
if (strpos($url, 'www.youtube.com/watch') !== false) {
$apikey = 'AIzaSyCPeA3MlMPeT1CU18NHfJawWAx18VoowOY';
$videoId = explode('&', explode("=", $url)[1])[0];
$url = 'https://www.googleapis.com/youtube/v3/videos?id=' . $videoId . '&key=' . $apikey . '&part=snippet';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response);
$value = json_decode(json_encode($data), true);
$title = $value['items'][0]['snippet']['title'];
} else {
set_error_handler(
function () {
return false;
}
);
if (($str = file_get_contents($url)) === false) {
$title = $url;
} else {
preg_match("/\<title\>(.*)\<\/title\>/i", $str, $title);
$title = $title[1];
if (preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $title))
$title = utf8_encode($title);
$title = html_entity_decode($title);
}
restore_error_handler();
}
} catch (Exception $e) {
$title = $url;
}
return $title;
}
Solution 16 - Php
if (!file_get_contents($data)) {
exit('<h1>ERROR MESSAGE</h1>');
} else {
return file_get_contents($data);
}
Solution 17 - Php
This will try to get the data, if it does not work, it will catch the error and allow you to do anything you need within the catch.
try {
$content = file_get_contents($site);
} catch(\Exception $e) {
return 'The file was not found';
}