I am trying to see if a URL exists or not, and if it does not exist reset the variable containing the URL to an error page/image. However my attempt below sets every instance of PIC_URL to noimage.gif, regardless of if it exists and is accessible or not. What am I missing?
if (@fopen($_REQUEST[$PIC_URL],"r"))
{
$status = "1";
}
else if (!(@fopen($_REQUEST[$PIC_URL],"r"))
{
$status = "2";
}
if ( $status == "2" ) $PIC_URL = "http://www.tricityhomes.com/assets/images/noimage.gif";
The test on the else part looks redundant, and did you mean $_REQUEST['PIC_URL']
?
if (@fopen($_REQUEST['PIC_URL'],"r"))
{
$status = "1";
}
else
{
$status = "2";
}
There's plenty more wrong with it though. To test if a remote file exists, you'd be better off using file_exists, or even rolling your own method to perform a HEAD request.
use file_exists
or is_readable, and don't use raw value
You might want to try doing something similar to this
<?php
function url_exists($url) {
// Version 4.x supported
$handle = curl_init($url);
if (false === $handle)
{
return false;
}
curl_setopt($handle, CURLOPT_HEADER, false);
curl_setopt($handle, CURLOPT_FAILONERROR, true); // this works
curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") ); // request as if Firefox
curl_setopt($handle, CURLOPT_NOBODY, true);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
$connectable = curl_exec($handle);
curl_close($handle);
return $connectable;
}
?>
Source: http://uk.php.net/manual/en/function.file-exists.php#85246
the reason being is that as has been mentioned checking against the raw value of fopen is not the best idea and also that method does not take account of being redirected to error pages etc.