Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_get_contents good way to handle errors [duplicate]

Tags:

html

php

I am trying to error handle the file_get_contents method so even if the user enters an incorrect website it will echo an error message rather then the unprofessional

Warning: file_get_contents(sidiowdiowjdiso): failed to open stream: No such file or directory in C:\xampp\htdocs\test.php on line 6

I thought if i make a try and catch it will be able to catch the error but that did not work.

try  
{  
$json = file_get_contents("sidiowdiowjdiso", true); //getting the file content
}  
catch (Exception $e)  
{  
 throw new Exception( 'Something really gone wrong', 0, $e);  
}  
like image 884
Hashey100 Avatar asked Apr 21 '13 11:04

Hashey100


People also ask

What is the function file_get_contents () useful for?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string.

What will the file_get_contents () return?

The function returns the read data or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .

What is the difference between file_get_contents ($ file and file_get_contents ($ file?

They both read an entire file, but file reads the file into an array, while file_get_contents reads it into a string.


2 Answers

Try cURL with curl_error instead of file_get_contents:

<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = '';
if( ($json = curl_exec($ch) ) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}
else
{
    echo 'Operation completed without any errors';
}

// Close handle
curl_close($ch);
?>
like image 165
Andrey Volk Avatar answered Oct 19 '22 15:10

Andrey Volk


file_get_contents do not throw an exception in error, instead it returns false, so you can check if the returned value is false:

$json = file_get_contents("sidiowdiowjdiso", true);
if ($json === false) {
    //There is an error opening the file
}

This way you still get the warning, if you want to remove it, you need to put an @ in front of file_get_contents. (This is considered a bad practice)

$json = @file_get_contents("sidiowdiowjdiso", true);
like image 22
m4t1t0 Avatar answered Oct 19 '22 14:10

m4t1t0