How to detect 404 if using file_get_contents

$html = file_get_contents(url);

$p = '#<a[^>]+href=("|\\')http://([^.]+\\.)?mydomain\\.com[^>]+>#i';
if (preg_match($p, $html)) {

How can i process a 404 response code in this situation…is it possible? (ie) if the page looked (url) for isn’t found…

file_get_content() will return false if it fails. keep in mind it can fail for reasons other than a 404 as well.

if ($!html) {

Tried adding that

elseif (!$html) {

i get errors displaying and then the 404 echoed:

Warning: file_get_contents() [function.file-get-contents]: php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/mydomain/public_html/myscript.php on line 42

Warning: file_get_contents( [function.file-get-contents]: failed to open stream: Permission denied in /home/mydomain/public_html/myscript.php on line 42

Can i switch these errors off?

turn the display_errors setting off
you can do this in php.ini, .htaccess, or with ini_set()

btw i dont think thats a 404 not found type of error. does it work for other urls at all?

yes other urls work ok :slight_smile:

Don’t turn error reporting off just add @ infront of file_get_contents

Sorry, where do you mean?


Thanks, so what does that actually do? I mean i see it stops the errors displaying, is that it’s purpose?

Yes, it is: Error Control Operators

Ah, excellent. Cheers php_daemon :slight_smile:

Why not just read the headers?