Friday, August 7, 2009

Php check File exists

When we are working with the directory structure we are in need of checking the files whether the file exists in the particular directory structure or not. In PHP we have the predefined function called file_exists() which checks the directory structure and returns a Boolean variable as the output. We can also check the file extension of the selected file also.
Here we may need only certain type of files to be displayed in a list of files. Like we may have the file name starting with "testing".

Below is an example which demonstrates the file_exists function and if the file exists then it checks for the file extension condition.


//==========
// Configuration
//==========
$directory = '/var/www/'; //Folder path
$lookingfor = 'testing'; //what to look for


$flag = false;
$ext = array( '.jpg' , '.gif' , '.png' );
for( $i = 0; count( $ext ) > $i; $i++ )
{
if( file_exists( $directory . $lookingfor . $ext[$i] ) )
{
$flag = true;
$name = $lookingfor . $ext[$i];
}
}

if( $flag == true )
{
echo 'found file!';
//echo $name;
}
?>

0 comments:

Post a Comment