Check file existence in php

by Php Ninza on July 14, 2009

Php developers need to do a lot of file operations , Work like cache building, logs etc all required file operations functions in php.

www.php.net/file_exists is a handy tool for existing file on to the webserver.

here’s a example code:-

< ?php
$file = '/path/foo.txt';
if (file_exists($file)) {
    echo "$file exists";
} else {
    echo "$file does not exist";
}
?>

This Functions returns TRUE if the file or directory specified by the filename exists otherwise it retuns FALSE .

Be Sociable, Share!

{ 4 comments… read them below or Shout @ me! }

Sean O July 17, 2009 at 2:14 pm

Or, use the ternary operator for one line of code:
echo ( file_exists($file) ) ? “$file exists” : “$file does not exist”;

Reply

Php Ninza July 18, 2009 at 12:47 am

@Sean
Thanks for stopping by. :)

Ternary operators are sometime difficult to be grasped by newbie coders and this post was directed to them , However the information is useful

Reply

John Gresham October 16, 2009 at 3:00 am

This is part of what I need to do. How can this be adapted to check if a page exists and if true load that page or if false load a different page, with everything happening silently (no messages echoed or 404 displayed)? Can anyone help? I’m new at PHP and can’t seem to find the answer. Thank you so much.

Reply

Php Ninza October 22, 2009 at 8:39 am

@John
Just replace the echo statements with the header redirects which will redirect to particular locations, You can find the header function at http://www.php.net/header

Hope it helps.

Reply

Leave a Comment

Previous post:

Next post: