PHP file_exists() Examples


file_exists() function checks whether a file or directory exist or not. It returns TRUE if exists, otherwise FALSE.

<?PHP
   $file = "/usr/test.txt";
   if (file_exists($file)) echo "file exists";
   $base = basename($file);
   if (file_exists($base)) echo "directory exists";
?>

To check a web file exists or not:
<?PHP
    $url="http://www.endmemo.com/program/php/fileexists.php";
	$headers = @get_headers($url);
	if(strpos($headers[0],'200')===false)
	{
		echo "$url not exists!\n";
	}
	else echo "$url exists\n";
?>

To get all files in a directory with certain pattern, use glob() function:
<?PHP
    $dir = "/usr/";
	$arrfiles = glob('*.txt');
	var_dump($arrfiles);
?>