12 January 2012

How to check if a file exists on remote/local server using php

Linking to a file or displaying an image from remote server is very common practice these days. But problem occurs when the file is not there on the remote server and our page starts showing a broken link. For this problem I have few solutions that will help you in avoiding this issue.

Solution # 1: Using file_exists()

Syntax
file_exists(string $filename)



Example
<?php 
if (file_exists("http://www.example.com/abc.jpg"))
    echo "File Exists";
else 
    echo "File does not Exists";
?>
You can use the name and location of the file if it is on the same server or the complete path for remote file. Sometimes this function does not work for remote files.

Solution # 2: Using is_file()

Syntax
is_file(string $filename)

Example
<?php 
if (is_file("http://www.example.com/abc.jpg"))
    echo "File Exists";
else 
    echo "File does not Exists";
?>
In is_file(), similar to file_exists(), you can use both file name and the complete path but this function also fails sometimes for remote files.
 
Solution # 3: Using fopen()

Syntax
fopen(string $filename,string $mode)

Example
<?php 
if (@fopen("http://www.example.com/abc.jpg","r"))
    echo "File Exists";
else 
    echo "File does not Exists";
?>
fopen() requires two arguments filename and mode, both are mandatory. This function has many modes but we are using "r" readonly mode for our purpose. Also "@" is used before fopen to avoid the warning it gives if file is not present. This method always works but it is a very untidy way of achieving what we want to do. It consumes more time then any other method.

3 comments:

Anonymous said...

It keep on telling me the file does not exists.

Why?

Udayraj Khatri said...

Does not working.
I got the solution to use the @file_get_contents() to check the URL and check the Boolean value.

danangnurfauzi said...

it works for no.3 solution..thanks