(PHP 4, PHP 5)
file_exists — 检查文件或目录是否存在
$filename
)检查文件或目录是否存在。
filename
文件或目录的路径。
在 Windows 中要用 //computername/share/filename 或者 \\computername\share\filename 来检查网络中的共享文件。
如果由 filename
指定的文件或目录存在则返回
TRUE
,否则返回 FALSE
。
Note:
This function will return
FALSE
for symlinks pointing to non-existing files.
如果因为安全模式的限制而导致不能访问文件的话,该函数会返回
FALSE
。然而,可以使用
include 来包含,如果文件在
safe_mode_include_dir
所指定的目录里。
Note:
The check is done using the real UID/GID instead of the effective one.
Note: 因为 PHP 的整数类型是有符号整型而且很多平台使用 32 位整型,对 2GB 以上的文件,一些文件系统函数可能返回无法预期的结果 。
Example #1 测试一个文件是否存在
<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
失败时抛出E_WARNING
警告。
Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。
自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。
junya (2013-01-06 12:11:18)
On Japanese Windows system, here is the other way to figure out the file existence to avoid SJIS 5C problem.
<?php
function sjis_file_exists($filename)
{
return exec("if exist \"$filename\" (echo 1) else (echo 0)");
}
?>
DeyV at poczta dot php dot pl (2012-01-13 04:47:19)
Great alternative to file_exists() is stream_resolve_include_path()
www dot freev at gmail dot com (2011-07-27 06:17:23)
my function filexists() function search file firts in include_path:
<?php
function filexists($file)
{
$ps = explode(":", ini_get('include_path'));
foreach($ps as $path)
{
if(file_exists($path.'/'.$file)) return true;
}
if(file_exists($file)) return true;
return false;
}
?>
spark at limao dot com dot br (2011-04-13 07:26:53)
this code here is in case you want to check if a file exists in another server:
<?php
function fileExists($path){
return (@fopen($path,"r")==true);
}
?>
unfortunately the file_exists can't reach remote servers, so I used the fopen function.
anthonyiacono at gmail dot com (2010-11-12 21:18:22)
Try this replacement if you are having issues with safe mode restrictions:
<?php
function file_exists_2($dir, $file)
{
$ret = exec("ls ".$dir." | grep ".$file);
return (!empty($ret));
}
?>
I was having an issue because Apache kept resetting permissions for my public_html directory, causing issues with safe mode.
_ michael (2010-09-05 14:16:42)
There is a subtle difference in behaviour of file_exists(), depending on the OS. Suppose you test a path ending with a slash. If the corresponding filesystem object exists, but is not a directory but a file, file_exists() will return true on Windows and false on Linux.
Ie, file_exists( $path_from_root . '/somedir/file/' ) returns true on Windows if that file exists, and false on Linux.
Tested with PHP 5.3.3 on Ubuntu and PHP 5.2.9 on Windows.
hex (2010-05-06 23:11:58)
If you simply want to check that some file (not directory) exists, and concerned about performance, try is_file() instead.
I timed is_file and file_exists, it seems like is_file() is almost 2x faster when a file exists and about the same when it doesn't.
ferodano at gmail dot com (2009-09-16 13:54:56)
You could use document root to be on the safer side because the function does not take relative paths:
<?php
if( file_exists( $_SERVER{'DOCUMENT_ROOT'} . "/my_images/abc.jpg")) {
...
}
?>
Do not forget to put the slash '/', e.g. my doc root in Ubuntu is /var/www without the slash.
plsnhat at gmail dot com (2009-07-31 07:30:29)
Since file_exists does not offer a possibility to search in include_path..
<?php
/*
* Expanden file_exists function
* Searches in include_path
*/
function file_exists_ip($filename) {
if(function_exists("get_include_path")) {
$include_path = get_include_path();
} elseif(false !== ($ip = ini_get("include_path"))) {
$include_path = $ip;
} else {return false;}
if(false !== strpos($include_path, PATH_SEPARATOR)) {
if(false !== ($temp = explode(PATH_SEPARATOR, $include_path)) && count($temp) > 0) {
for($n = 0; $n < count($temp); $n++) {
if(false !== @file_exists($temp[$n] . $filename)) {
return true;
}
}
return false;
} else {return false;}
} elseif(!empty($include_path)) {
if(false !== @file_exists($include_path)) {
return true;
} else {return false;}
} else {return false;}
}
?>
pgl at yoyo dot org (2009-07-31 07:03:45)
Note that this will return false for streams, eg, php://stdin.
jbeltran (2009-05-20 13:39:48)
I want to warn developers using PHP 5.0.4 of a bug that don't happen in current stable versions:
file_exists seems to cache the response, even when the file has been moved.
An example:
<?php
/*
When a file which has been called by file_exist
has been moved, the file_exist next call gives true again
*/
$f = "foo.txt";
file_put_contents( $f, "content" );
if(file_exists( $f )){
rename( $f, $f.".moved" );
}
if( file_exists( $f )){
echo "Wrong! the file has just been moved! file_exists should return false.";
rename( $f, $f.".willnotwork" ); //It gives a warning
}
?>
The same code tested in PHP 5.2.4-2ubuntu5.6 with Suhosin-Patch 0.9.6.2 (cli) behaves correctly.
joel atSymbol avial.com.au (2009-04-12 18:52:49)
I wanted to check for the existance of a file with the same name, but disregarding case. Here is what I came up with:
<?php
/**
* Alternative to file_exists() that will also return true if a file exists
* with the same name in a different case.
* eg. say there exists a file /path/product.class.php
* file_exists('/path/Product.class.php')
* => false
* similar_file_exists('/path/Product.class.php')
* => true
*/
function similar_file_exists($filename) {
if (file_exists($filename)) {
return true;
}
$dir = dirname($filename);
$files = glob($dir . '/*');
$lcaseFilename = strtolower($filename);
foreach($files as $file) {
if (strtolower($file) == $lcaseFilename) {
return true;
}
}
return false;
}
?>
alexpechkarev at yahoo dot co dot uk (2009-03-06 04:28:49)
file_exists() function return FALSE for files inaccessible due to safe mode restrictions.
Here is the way to walk around and check if file exists on the server:
<?php
if( exec('ls -l images/ | grep image.jpg)){
echo "<img src='http://www.myaddress/images/image1.jpg'>";
}else{
echo "No IMAGE";
}
alkaaran at gmail dot com (2009-02-02 06:11:23)
Although PHP 5+ supports this function with FTP, it appears that file_exists() used on ftp will always return TRUE, even if the file or directory does not exist.
fabin dot gnu at gmail dot com (2009-01-31 01:03:41)
The code can be used to t a filename that can be used to create a new filename.
<?php
function generateRandomString($length = 8)
{
$string = "";
//character that can be used
$possible = "0123456789bcdfghjkmnpqrstvwxyz";
for($i=0;$i < $length;$i++)
{
$char = substr($possible, rand(0, strlen($possible)-1), 1);
if (!strstr($string, $char))
{
$string .= $char;
}
}
return $string;
}
function randomFile($folder = '', $extension = '')
{
$folder = trim($folder);
$folder = ($folder == '') ? './' : $folder;
//check if directory exist
if (!is_dir($folder)){ die('invalid folder given!'); }
//generate a filepath
$filepath = $folder . "/" . generateRandomString(128) . $extension;
//check if that filepath already exist, if it exist if generates again
//till if gets one that doesn't exist
while(file_exists($filepath))
{
$filepath = $folder . "/" . generateRandomString(128) . $extension;
}
return $filepath;
}
?>
kevin at cuznersoft dot com (2008-11-04 08:32:58)
My way of making sure files exist before including them is as follows (example: including a class file in an autoloader):
<?php
function __autoload($name)
{
$path = explode(":", ini_get('include_path')); //get all the possible paths to the file (preloaded with the file structure of the project)
foreach($path as $tryThis)
{
//try each possible iteration of the file name and use the first one that comes up
// name.class.php first
$exists = file_exists($tryThis . '/' . $name . '.class.php');
if ($exists)
{
include_once($name . '.class.php');
return;
}
//ok that didn't work, try the other way around
$exists = file_exists($tryThis . '/' . 'class.' . $name . '.php');
if ($exists)
{
include_once('class.' . $name . '.php');
return;
}
//neither did that...let's try as an inc.php
$exists = file_exists($tryThis . '/' . $name . '.inc.php');
if ($exists)
{
include_once($name . '.inc.php');
return;
}
}
// can't find it...
die("Class $name could not be found!");
}
?>
justin (2008-08-21 12:07:10)
Small adjustment to the url_exist() by marufit at gmail dot com. Some sites like digg.com for example check the HTTPHEADER to see who is requesting the page and will PHP will throw an error. Adding the following line fixes the issue:
curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") ); // request as if Firefox
<?php
function url_exists($url) {
// Version 4.x supported
$handle = curl_init($url);
if (false === $handle)
{
return false;
}
curl_setopt($handle, CURLOPT_HEADER, false);
curl_setopt($handle, CURLOPT_FAILONERROR, true); // this works
curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") ); // request as if Firefox
curl_setopt($handle, CURLOPT_NOBODY, true);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
$connectable = curl_exec($handle);
curl_close($handle);
return $connectable;
}
?>
Avee (2008-08-19 08:21:26)
I made a bit of code that sees whether a file served via RTSP is there or not:
<?php
function rtsp_exists($url) {
$server = parse_url($url, PHP_URL_HOST);
$port = "554";
$hdrs = "DESCRIBE " .$url ." RTSP/1.0"."\r\n\r\n";
//Open connection (15s timeout)
$sh = fsockopen($server, $port, $err, $err_otp, 15);
//Check connections
if(!$sh) return false;
//Send headers
fputs($sh,$hdrs);
//Receive data (1KB)
$rtds = fgets($sh, 1024);
//Close socket
fclose($sh);
return strpos($rtds, "200 OK") > 0;
}
?>
dan at sudonames dot com (2008-08-05 17:41:52)
Here is a simpler version of url_exists:
<?php
function url_exists($url) {
$hdrs = @get_headers($url);
return is_array($hdrs) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$hdrs[0]) : false;
}
?>
stuart (2008-02-26 10:44:49)
When using file_exists, seems you cannot do:
<?php
foreach ($possibles as $poss)
{
if ( file_exists(SITE_RANGE_IMAGE_PATH .$this->range_id .'/ '.$poss .'.jpg') )
{
// exists
}
else
{
// not found
}
}
?>
so you must do:
<?php
foreach ($possibles as $poss)
{
$img = SITE_RANGE_IMAGE_PATH .$this->range_id .'/ '.$poss .'.jpg'
if ( file_exists($img) )
{
// exists
}
else
{
// not found
}
}
?>
Then things will work fine.
This is at least the case on this Windows system running php 5.2.5 and apache 2.2.3
Not sure if it is down to the concatenation or the fact theres a constant in there, i'm about to run away and test just that...
jaz-t at hotmail dot com (2008-02-26 07:12:47)
Note on openspecies entry (excellent btw, thanks!).
If your server cannot resolve its own DNS, use the following:
$f = preg_replace('/www\.yourserver\.(net|com)/', getenv('SERVER_ADDR'), $f);
Just before the $h = @get_headers($f); line.
Replace the extensions (net|com|...) in the regexp expression as appropriate.
EXAMPLE:
File you are checking for: http://www.youserver.net/myfile.gif
Server IP: 10.0.0.125
The preg_replace will effectively 'resolve' the address for you by assigning $f as follows:
http://10.0.0.125/myfile.gif
maurice at idify dot nl (2007-11-20 02:45:16)
Note: The results of this function are cached. See clearstatcache() for more details.
That's a pretty big note. Don't forget this one, since it can make your file_exists() behave unexpectedly - probably at production time ;)
marufit at gmail dot com (2007-11-12 03:22:04)
Older php (v4.x) do not work with get_headers() function. So I made this one and working.
<?php
function url_exists($url) {
// Version 4.x supported
$handle = curl_init($url);
if (false === $handle)
{
return false;
}
curl_setopt($handle, CURLOPT_HEADER, false);
curl_setopt($handle, CURLOPT_FAILONERROR, true); // this works
curl_setopt($handle, CURLOPT_NOBODY, true);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
$connectable = curl_exec($handle);
curl_close($handle);
return $connectable;
}
?>
ktcb123 at hotmail dot com (2007-10-22 00:26:37)
For some reason, none of the url_exists() functions posted here worked for me, so here is my own tweaked version of it.
<?php
function url_exists($url){
$url = str_replace("http://", "", $url);
if (strstr($url, "/")) {
$url = explode("/", $url, 2);
$url[1] = "/".$url[1];
} else {
$url = array($url, "/");
}
$fh = fsockopen($url[0], 80);
if ($fh) {
fputs($fh,"GET ".$url[1]." HTTP/1.1\nHost:".$url[0]."\n\n");
if (fread($fh, 22) == "HTTP/1.1 404 Not Found") { return FALSE; }
else { return TRUE; }
} else { return FALSE;}
}
?>
guillermogomezruiz at gmail dot com (2007-09-07 04:08:31)
I was having problems with the file_exists when using urls, so I made this function:
<?php
function file_exists_2($filePath)
{
return ($ch = curl_init($filePath)) ? @curl_close($ch) || true : false;
}
?>
Cheers!
worldclimb at gmail dot com (2007-07-19 14:48:03)
Small error in florinel2k's example
$sourcePath should be $fileUrl, otherwise it works well for me.
//Corrected
This is an example if you want to know that a file exists (if that file isn't on your server):
$fileUrl = "http://www.examplecom/test.jpg";
$AgetHeaders = @get_headers($fileUrl);
if (preg_match("|200|", $AgetHeaders[0])) {
// file exists
} else {
// file doesn't exists
}
openspecies (2007-07-17 06:21:09)
/*
* EXTERN/FS FILE
* a simple alternative without cURL
*/
function sys_file_exists($f = NULL)
{
$h = array();
$ret = FALSE;
if(!is_null($f)):
if(preg_match('/^http|https|ftp/',$f)): //test protocol EXTERN
$h = @get_headers($f);
if(array_key_exists(0,$h)) :
$ret = (bool) preg_match('/200|301/',$h[0]); /* HTTP/1.1 301 DAP (directory) */
endif;
else: //else FS
$ret = (file_exists($f) && is_readable($f));
endif;
endif;
return (($ret === TRUE) ? TRUE : FALSE);
}
then, it's easy to replace file_exists in your code,
grep -R file_exists path/to/frameworks
...
private function _loadModel($file = NULL)
{
//TRACE($file);
try {
if(is_null($file) || !sys_file_exists($file)) :
throw new SF_websiteview_exception('loadModel : '.$file.' could not be loaded');
endif;
} catch(SF_websiteview_exception $ex){$ex->trace(FALSE);}
return file_get_contents($file);
}
...
private function _loadtable($file)
{
try {
if(sys_file_exists($file)):
$buf = file($file);
else:
throw new SF_localization_exception('Table '.$this->tablename.' could not be loaded');
endif;
} catch(SF_localization_exception $ex){$ex->trace(TRUE);$ex->__exit();}
$tbl = array();
$i = 0;
while ($i < count($buf) ) :
if (preg_match('/"(.*)"+[ = ]+"(.*)";+$/',trim($buf[$i]),$row) && !preg_match("/^[\/\/|\/\*]/",$buf[$i])) :
$tbl[$row[1]] = $row[2];
endif;
$i++;
endwhile;
$this->table = $tbl;
unset($tbl,$buf);
}
...
@+
pcdinh at phpvietnam dot net (2007-07-14 07:03:57)
In response to havran at gmail dot com
Your function url_exists() does not work because it has got a big bug. curl_init does not make a connection to that url until curl_exec() is executed. The return value from curl_init() shows if a curl session can be started.
That function can be rewritten as follows
<?php
class Url
{
/**
* Check if an url is existed
*
* @param string $url
* @access static
* @return bool True if the url is accessible and false if the url is unaccessible or does not exist
* @throws Exception An exception will be thrown when Curl session fails to start
*/
public static function exists($url)
{
if (null === $url || '' === trim($url))
{
throw new Exception('The url to check must be a not empty string');
}
$handle = curl_init($url);
if (false === $handle)
{
throw new Exception('Fail to start Curl session');
}
curl_setopt($handle, CURLOPT_HEADER, false);
curl_setopt($handle, CURLOPT_NOBODY, true);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
// grab Url
$connectable = curl_exec($handle);
// close Curl resource, and free up system resources
curl_close($handle);
return $connectable;
}
}
?>
How to use:
<?php
try
{
if (Url::exists('http://phpvietnam.net'))
{
// Do something here
}
}
catch (Exception $ex)
{
// Do something here
}
?>
clancyhood at gmail dot com (2007-07-06 21:23:53)
Full-featured function to check if a file exists on an external server
Using snippets of code from below and some of my own I knocked this up because I wanted to check a URL from user input, and to be able to tell exactly what is wrong with a URL, not simply if it's true or false. This function also bypasses any need for the server to check for URLs that simply aren't going to exist
I got the big list of domain tlds from http://data.iana.org/TLD/tlds-alpha-by-domain.txt
<?php
### check file exists on external server - returns numeric values for false, a full URL string for true.
// ext = optional file extension, like html, mp3, jpg... stops checking if doesn't meet this condition
function xfile_404($file, $ext=false){
$file = ereg_replace(' +', '%20', trim($file));
if(substr($file, 0, 7) !== "http://"){ $file = "http://" . $file; }
if($ext){
$file_ext = strtolower(array_pop(explode('.', $file)));
if($file_ext !== $ext){
return 1;
break;
}
}
$domain = substr($file, 7); //lose the http prefix
$domain_ext = strtoupper(array_pop(explode('.', substr($domain, 0, strpos($domain, '/'))))); // end up with 'com' or 'net' or something
$types = array('AC', 'AD', 'AE', 'AERO', 'AF', 'AG', 'AI', 'AL', 'AM', 'AN', 'AO', 'AQ', 'AR', 'ARPA', 'AS', 'ASIA', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BIZ', 'BJ', 'BM', 'BN', 'BO', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CAT', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'COM', 'COOP', 'CR', 'CU', 'CV', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EDU', 'EE', 'EG', 'ER', 'ES', 'ET', 'EU', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GOV', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'INFO', 'INT', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JOBS', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LOCAL', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'MG', 'MH', 'MIL', 'MK', 'ML', 'MM', 'MN', 'MO', 'MOBI', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MUSEUM', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NAME', 'NC', 'NE', 'NET', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'ORG', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PRO', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'ST', 'SU', 'SV', 'SY', 'SZ', 'TC', 'TD', 'TEL', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TP', 'TR', 'TRAVEL', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UK', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'YU', 'ZA', 'ZM', 'ZW');
if(!in_array($domain_ext, $types)){
return 2;
break;
}
$file_headers = @get_headers($file);
if(!$file_headers){
return 3;
break;
}
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
return 404;
}else{
return ereg_replace('%20', ' ', $file);
}
}
### Test it out
$url = "www.sameindeath.com/MJ13/mp3/singlephile.mp3";
if(!is_numeric(xfile_404($url))){ // it exists
if(!is_numeric(xfile_404($url, 'mp3'))){ // it exists, and it's the type of file we want it to be
// Note that you can also use the array returned from
$file_headers = @get_headers($file);
// to determine file type and file size also. Woopee!
?>
bvazquez at siscomx dot com (2007-07-04 09:13:23)
If you are trying to access a Windows Network Share you have to configure your WebServer with enough permissions for example:
$file = fopen("\\siscomx17\c\websapp.log",'r');
You will get an error telling you that the pathname doesnt exist this will be because Apache or IIS run as LocalSystem so you will have to enter to Services and configure Apache on "Open a session as" Create a new user that has enough permissions and also be sure that target share has the proper permissions.
Hope this save some hours of research to anyone.
florinel2k at yahoo dot com (2007-06-13 01:23:10)
This is an example if you want to know that a file exists (if that file isn't on your server):
$fileUrl = "http://www.examplecom/test.jpg";
$AgetHeaders = @get_headers($sourcePath);
if (preg_match("|200|", $AgetHeaders[0])) {
// file exists
} else {
// file doesn't exists
}
vernon at kesnerdesigns dot net (2007-05-10 08:44:49)
In response to seejohnrun's version to check if a URL exists. Even if the file doesn't exist you're still going to get 404 headers. You can still use get_headers if you don't have the option of using CURL..
$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
havran at gmail dot com (2007-04-12 10:56:27)
Function url_exists() through CURL.
<?php
function url_exists($url) {
if (!$fp = curl_init($url)) return false;
return true;
}
?>
stephen dot reay at mac dot com (2007-03-27 19:28:36)
developing a CMS, with a link checker, it caused issues that when running on Win32, file_exists shows no error for case differences between the file on disk and the file you query for. this causes an issue when putting content created on the Win32 box onto a *NIX box.
the following is a function to test for files with case sensitivity, regardless of the OS. it returns 1 for a match, 0 for fails, and 2 if the file exists but with a different case.
function file_exists_case($strUrl)
{
$realPath = str_replace('\\','/',realpath($strUrl));
if(file_exists($strUrl) && $realPath == $strUrl)
{
return 1; //File exists, with correct case
}
elseif(file_exists($realPath))
{
return 2; //File exists, but wrong case
}
else
{
return 0; //File does not exist
}
}
seejohnrun at gmail dot com (2007-03-22 19:55:32)
not to overshadow anyone making url_exists functions, but...
function url_exists($url) {
if ((strpos($url, "http")) === false) $url = "http://" . $url;
if (is_array(@get_headers($url)))
return true;
else
return false;
}
enjoy!
earle dot west at transactionalweb dot com (2007-03-14 17:49:55)
If the file being tested by file_exists() is a file on a symbolically-linked directory structure, the results depend on the permissions of the directory tree node underneath the linked tree. PHP under a web server (i.e. apache) will respect permissions of the file system underneath the symbolic link, contrasting with PHP as a shell script which respects permissions of the directories that are linked (i.e. on top, and visible).
This results in files that appear to NOT exist on a symbolic link, even though they are very much in existance and indeed are readable by the web server.
Vladimir Sokolov (2007-02-12 05:24:01)
Updated funtion url_exist
It work right!
http://www.bbc.co.uk/newsa/n5ctrl/progs/frost/latest.ram - (true)
http://www.bbc.co.uk/newsa/n5ctrl/progs/frost/latest1.ram - (false)
http://www.bbc.co.uk/newsa/n5ctrl/progs/frost1/latest.ram -
(false)
-----
<?php
function url_exists($url) {
$a_url = parse_url($url);
if (!isset($a_url['port'])) $a_url['port'] = 80;
$errno = 0;
$errstr = '';
$timeout = 30;
if(isset($a_url['host']) && $a_url['host']!=gethostbyname($a_url['host'])){
$fid = fsockopen($a_url['host'], $a_url['port'], $errno, $errstr, $timeout);
if (!$fid) return false;
$page = isset($a_url['path']) ?$a_url['path']:'';
$page .= isset($a_url['query'])?'?'.$a_url['query']:'';
fputs($fid, 'HEAD '.$page.' HTTP/1.0'."\r\n".'Host: '.$a_url['host']."\r\n\r\n");
$head = fread($fid, 4096);
$head = substr($head,0,strpos($head, 'Connection: close'));
fclose($fid);
if (preg_match('#^HTTP/.*\s+[200|302]+\s#i', $head)) {
$pos = strpos($head, 'Content-Type');
return $pos !== false;
}
} else {
return false;
}
}
?>
adam at darkhousemedia dot com (2007-01-13 13:10:43)
In regards to the function url_exists below... the reason it's slow is because of fopen().
I tried this function with a loop of 25 urls, and output the time spent using microtime(), which ended up taking 4.6 seconds.
I wrote a new function using fsockopen() and tried with the same 25 urls. Time spent, 1.1 seconds. More than 4 times as fast.
Another issue with it, I don't know if this is a problem or not, but fopen() returns true if the url results in a 500 Internal Server Error. fsockopen() returns false in this case.
I don't know if this is the fastest/most efficient method, but I think it's a nice alternative regardless. Here's the function:
<?php
function url_exists($url){
if(strstr($url, "http://")) $url = str_replace("http://", "", $url);
$fp = @fsockopen($url, 80);
if($fp === false) return false;
return true;
}
?>
pilotdoofy at gmail dot com (2006-04-22 13:35:29)
I wrote a very simple function that allows you to search a folder for a file name with a regular expression. It can handle both PREG and EREG regexps and can accept different case sensitivities for EREG regexps.
function regExpFile($regExp, $dir, $regType='P', $case='') {
# Two parameters accepted by $regType are E for ereg* functions
# and P for preg* functions
$func = ( $regType == 'P' ) ? 'preg_match' : 'ereg' . $case;
# Note, technically anything other than P will use ereg* functions;
# however, you can specify whether to use ereg or eregi by
# declaring $case as "i" to use eregi rather than ereg
$open = opendir($dir);
while( ($file = readdir($open)) !== false ) {
if ( $func($regExp, $file) ) {
return true;
}
} // End while
return false;
} // End function
Basically if you supply anything but "P" for $regType it will assume you're using EREG regexps. The case should only be blank or "i".
hiro at arkusa dot com (2006-02-07 13:23:18)
As of php 5.0.4, many (if not all) php file manipulation functions fail if a file's size is no smaller than 2GB (i.e. 2^31) on the x86 platforms. Even file_exists() fails (always returns FALSE). This puzzled me when I was writing a video file manipulation application.
A simple alternative is like:
function file_exists_2gb($filename) {
system("test -f $filename", $rval);
return ($rval == 0);
}
(2006-01-07 13:08:15)
I wrote this little handy function to check if an image exists in a directory, and if so, return a filename which doesnt exists e.g. if you try 'flower.jpg' and it exists, then it tries 'flower[1].jpg' and if that one exists it tries 'flower[2].jpg' and so on. It works fine at my place. Ofcourse you can use it also for other filetypes than images.
<?php
function imageExists($image,$dir) {
$i=1; $probeer=$image;
while(file_exists($dir.$probeer)) {
$punt=strrpos($image,".");
if(substr($image,($punt-3),1)!==("[") && substr($image,($punt-1),1)!==("]")) {
$probeer=substr($image,0,$punt)."[".$i."]".
substr($image,($punt),strlen($image)-$punt);
} else {
$probeer=substr($image,0,($punt-3))."[".$i."]".
substr($image,($punt),strlen($image)-$punt);
}
$i++;
}
return $probeer;
}
?>
Fabrizio (staff at bibivu dot com) (2005-12-21 18:11:16)
here a function to check if a certain URL exist:
<?php
function url_exists($url) {
$a_url = parse_url($url);
if (!isset($a_url['port'])) $a_url['port'] = 80;
$errno = 0;
$errstr = '';
$timeout = 30;
if(isset($a_url['host']) && $a_url['host']!=gethostbyname($a_url['host'])){
$fid = fsockopen($a_url['host'], $a_url['port'], $errno, $errstr, $timeout);
if (!$fid) return false;
$page = isset($a_url['path']) ?$a_url['path']:'';
$page .= isset($a_url['query'])?'?'.$a_url['query']:'';
fputs($fid, 'HEAD '.$page.' HTTP/1.0'."\r\n".'Host: '.$a_url['host']."\r\n\r\n");
$head = fread($fid, 4096);
fclose($fid);
return preg_match('#^HTTP/.*\s+[200|302]+\s#i', $head);
} else {
return false;
}
}
?>
in my CMS, I am using it with those lines:
<?php
if(!isset($this->f_exist[$image]['exist']))
if(strtolower(substr($fimage,0,4)) == 'http' || strtolower(substr($fimage,0,4)) == 'www.'){
if(strtolower(substr($image,0,4)) == 'www.'){
$fimage = 'http://'.$fimage;
$image = 'http://'.$image;
}
$this->f_exist[$image]['exist'] = $this->url_exists($fimage); //for now
} else {
$this->f_exist[$image]['exist'] = ($fimage!='' && file_exists($fimage) && is_file($fimage) && is_readable($fimage) && filesize($fimage)>0);
}
}
?>
flobee (2005-12-13 04:24:59)
file_exists overwrites the last access (atime) !
try:
if (@fclose(@fopen( $file, "r"))) {
// true;
} else {
// false;
}
to check if important for you
ihoss dot com at gmail dot com (2005-10-19 07:37:48)
The following script checks if there is a file with the same name and adds _n to the end of the file name, where n increases. if img.jpg is on the server, it tries with img_0.jpg, checks if it is on the server and tries with img_1.jpg.
<?php
$img = "images/".$_FILES['bilde']['name'];
$t=0;
while(file_exists($img)){
$img = "images/".$_FILES['bilde']['name'];
$img=substr($img,0,strpos($img,"."))."_$t".strstr($img,".");
$t++;
}
move_uploaded_file($_FILES['bilde']['tmp_name'], $img);
?>
phenbach at phenbach dot com (2005-09-19 15:37:36)
I recently had an issue with PLESK and copying file to other directories with the move_uploaded file function.
This would work on every linux server except plesk servers. I could figure it out and have yet to find out. I had to create a work a round and decided to use the exec() function.
As noted above the file_exist() function must need to wait for some time and I found the looking function a waste of resouces and didn't work for me anyway. So this is what I came up with.
function cp($source,$destination){
$cmd="cp -u ".$source ." ".$destination; //create the command string to copy with the update option
exec($cmd); //exec command
$cmd_test="ls -la ".$destination; //list file
exec($cmd_test,$out);
//If the file is present it $out[0] key will contain the file info.
//if it is not present it will be null
if (isset($out[0])){
return true;
}else{
return false;
}
}
davidc at php dot net (2005-09-13 13:05:06)
Also while using the file_exists file, please make sure you do not start using stuff like,
<?php
if(file_exists($_GET['file'] . '.php')) {
include($_GET['file'] . '.php';
}
?>
you could use something like this..
<?php
$inrep = "./";
$extfichier = ".php";
$page = $inrep.basename(strval($_REQUEST["page"]),$extfichier).extfichier;
if(file_exist($page)) {
include($page);
}
?>
or even hardcode it.
So since pretty much all commercial server(s) have url_fopen on.. you can imagine that file_exists($_GET['file']. '.php')
is rather .. unsecure :)
-David Coallier
tma at 2p dot cz (2005-08-24 01:47:59)
If checking for a file newly created by an external program in Windows then file_exists() does not recognize it immediately. Iy seems that a short timeout may be required.
<?
$file = 'file.tmp';
if ($h = popen("start \"bla\" touch $file", "r")) {
pclose($h);
// now I would like know if a file was created
// note: usleep not supported
$start = gettimeofday();
while (!file_exists(trim($file, " '\""))) {
$stop = gettimeofday();
if ( 1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec'] > 500000) break; // wait a moment
}
if (file_exists($file)) // now should be reliable
?>
(2005-08-09 07:20:03)
That is true feshi. But, if you have your server configured correctly, those access logs will only be accessible by an admin or the root account. The webuser account that runs the php script will be unable to start reading from that file. That's the easiest fix.
feshi (2005-08-04 03:34:58)
this code looks inocent
<?php
$filename=$_REQUEST["var"];
$filename .= ".data";
file_exist($filename){
include($filename);
}
?>
but if you pass something like script.php?var=test%00asbs
it should really can do bad things like including accesslog files if you replace "test" with something like "../logs/accesslog"
(2005-03-07 02:00:20)
Nathaniel, you should read the manual carefuly next time prior to posting anything here, as all you indicated is the fact you missed the idea of the include_path. To remind - include_path is for some functions only, mainly intended for include and require to simpify include/require operations (kinda way the #include works). It is NOT for any filesystem function, which would be damn annoying than helpful, which is quite understandable and obvious.
andrewNOSPAMPLEASE at abcd dot NOSPAMERSca (2005-02-11 05:29:07)
file_exists will have trouble finding your file if the file permissions are not read enabled for 'other' when not owned by your php user. I thought I was having trouble with a directory name having a space in it (/users/andrew/Pictures/iPhoto Library/AlbumData.xml) but the reality was that there weren't read permissions on Pictures, iPhoto Library or AlbumData.xml. Once I fixed that, file_exists worked.
Nathaniel (2005-02-08 21:08:15)
I spent the last two hours wondering what was wrong with my if statement: file_exists($file) was returning false, however I could call include($file) with no problem.
It turns out that I didn't realize that the php include_path value I had set in the .htaccess file didn't carry over to file_exists, is_file, etc.
Thus:
<?PHP
// .htaccess php_value include_path '/home/user/public_html/';
// includes lies in /home/user/public_html/includes/
//doesn't work, file_exists returns false
if ( file_exists('includes/config.php') )
{
include('includes/config.php');
}
//does work, file_exists returns true
if ( file_exists('/home/user/public_html/includes/config.php') )
{
include('includes/config.php');
}
?>
Just goes to show that "shortcuts for simplicity" like setting the include_path in .htaccess can just cause more grief in the long run.
alex at raynor nospam dot ru (2004-04-05 08:16:55)
If you use open_basedir in php.ini and use file_exists for file outside open_basedir path, you will not be warned at log and file_exists returns false even if file really exists.
(2004-02-11 18:32:27)
On nix systems file_exists will report a link that doesn't point to a valid file as non-existant, ie: the link itself exists but the file it points to does not. Using is_link will report true whether the link points to a valid file or not.