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 }
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.
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.
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.
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'); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With