Dan Sewell Dan Sewell - 1 year ago 57
PHP Question

PHP File checking always returning false

This bit of code reads from an RSS feed and shoulfd detect if an image exisists on the server or not:

$feedURL = 'http://www.goapr.com/news/category/product-release/feed/';
$sxml = @simplexml_load_file($feedURL);
foreach($sxml->channel as $channel){
foreach($channel->item as $item){
$i += 1;

$file = 'http://www.goapr.co.uk'. $item->prodimg;

if (file_exists($file)) {
echo "The file $file exists";
} else {
echo "The file $file does not exist";

echo 'Sorry there was an error. The recent products will return shortly.';

Many of the images do exist, but it returns all images not found:

The file http://www.goapr.co.uk/includes/img/newprod/ultras4.png does not existThe file http://www.goapr.co.uk/includes/img/newprod/30tpulleys.png does not existThe file http://www.goapr.co.uk/includes/img/newprod/tiguan.png does not existThe file http://www.goapr.co.uk/includes/img/newprod/2325row.png does not existThe file http://www.goapr.co.uk/includes/img/newprod/plus.png does not existThe file http://www.goapr.co.uk/includes/img/newprod/2017r.png does not existThe file http://www.goapr.co.uk/includes/img/newprod/v24gti.png does not existThe file http://www.goapr.co.uk/includes/img/newprod/q5gen3.png does not existThe file http://www.goapr.co.uk/includes/img/newprod/s8downpipes.png does not existThe file http://www.goapr.co.uk/products/
All images are detected as not found.

Its not the same as: How to check if a file exists from a url as the files are on the same filesystem as this PHP page.

Answer Source

If you need to check if a file on the local filesystem exists you should refer to it via it's local path and not its URL, something like:

$file = $_SERVER["DOCUMENT_ROOT"]."/path/to/images/".$item->prodimg; 

Note that the DOCUMENT_ROOT is the root path as set up by the webserver host (which means it may not work in the commandline.

You can also use __DIR__."/".$item->prodimg if the images are in the same directory as the currently running script.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download