开发者

PHP file exists

Using PHP I need to determine if a file exists.

I've tried file_exists() but the permissions are limited and I don't believe开发者_如何学JAVA PHP can read the file permissions. The file is a photo and can be viewed via a URL.

eg: http://www.seemeagain.com/users/1000002722/gallery_1312973080.jpg

I've tried is_readable() but I all results again are it doesn't exist.

I've also pointed by functions at index.php to test I was using them correctly and with index.php they return the correct expected results.

Is there a different PHP function I can use to test a file exists by chance or a trick?

thankyou...


I guess you could use file_get_contents. It returns false on a failure and the contents of a file on success: http://php.net/manual/en/function.file-get-contents.php


see file_exists not working for me. Short: file_exists will only check on your server, it is not used to check URLs. You can use curl etc. and check the header.

The documentation states:

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

This simply means it may work, but usually it won't.


In case you are trying to check a local file:
file_exists() function returns FALSE for files not accessible due to safe mode restrictions. So try this:

   function my_file_exists($dir, $file)
   {
       $ret = exec("ls ".escapeshellarg($dir)." | grep ".escapeshellarg($file));
       return (!empty($ret));
   } 


If PHP has no permissions to read the file, you won't be able to check file existence via file_exists() or is_readable() as these functions depend on being able to access the file locally on your server.

The only solution that will work out is checking if the file exists using a HTTP request.

Alex' solution with file_get_contents() is one way to do that, but you must check if

allow_url_fopen = true

in your php.ini, so

file_get_contents("http://www.seemeagain.com/users/1000002722/gallery_1312973080.jpg")

is allowed to retrieve data from HTTP (http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen).

As long as your file is readable via browser, you will be able to check for existance, but you still have to download the whole file, which produces a lot of traffic overhead and takes time.

My suggestion is to use

<?
$headers = get_headers("http://www.seemeagain.com/users/1000002722/gallery_1312973080.jpg");

if ($headers[0] == "HTTP/1.1 200 OK")
{
    // Your file does exist
}
elseif($headers[0] == "HTTP/1.1 404 Not Found")
{
    // Your file does not exist
}
else 
{
    // Some other headers...
    highlight_string(print_r($headers,1));
}

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜