Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_get_contents when url doesn't exist

I'm using file_get_contents() to access a URL.

file_get_contents('http://somenotrealurl.com/notrealpage'); 

If the URL is not real, it return this error message. How can I get it to error gracefully so that I know that the page doesn't exist and act accordingly without displaying this error message?

file_get_contents('http://somenotrealurl.com/notrealpage')  [function.file-get-contents]:  failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found  in myphppage.php on line 3 

for example in zend you can say: if ($request->isSuccessful())

$client = New Zend_Http_Client(); $client->setUri('http://someurl.com/somepage');  $request = $client->request();  if ($request->isSuccessful()) {  //do stuff with the result } 
like image 233
sami Avatar asked Dec 05 '10 09:12

sami


People also ask

What will the file_get_contents () return?

The file_get_contents() function returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. An E_WARNING level error is generated if filename cannot be found, maxlength is less than zero, or if seeking the specified offset in the stream fails.

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.

Is file_get_contents secure?

file_get_contents in itself appears safe, as it retrieves the URL and places it into a string. As long as you're not processing the string in any script engine or using is as any execution parameter you should be safe.


1 Answers

You need to check the HTTP response code:

function get_http_response_code($url) {     $headers = get_headers($url);     return substr($headers[0], 9, 3); } if(get_http_response_code('http://somenotrealurl.com/notrealpage') != "200"){     echo "error"; }else{     file_get_contents('http://somenotrealurl.com/notrealpage'); } 
like image 133
ynh Avatar answered Oct 11 '22 23:10

ynh