Hướng dẫn file_exists php

Hàm này kiểm tra xem file hoặc thư mục có tồn tại không.

Trả về TRUE nếu file hoặc thư mục được xác định bởi filename là tồn tại, nếu không là FALSE.

Đã có app VietJack trên điện thoại, giải bài tập SGK, SBT Soạn văn, Văn mẫu, Thi online, Bài giảng....miễn phí. Tải ngay ứng dụng trên Android và iOS.

Theo dõi chúng tôi miễn phí trên mạng xã hội facebook và youtube:

Các bạn ở Hà Nội có thể tham gia khóa học thứ 9 của vietjackteam [đang tuyển sinh] vào cuối tháng 10/2018 do anh Nguyễn Thanh Tuyền, admin vietjack.com trực tiếp giảng dạy tại Hà Nội. Chi tiết nội dung khóa học tham khỏa link : Khóa học Java.Các bạn học CNTT, điện tử viễn thông, đa phương tiện, điện-điện tử, toán tin có thể theo học khóa này. Số lượng các công việc Java hoặc .NET luôn gấp ít nhất 3 lần Android hoặc iOS trên thị trường tuyển dụng. Khóa online= Đi phỏng vấn, Khóa offline= Đi phỏng vấn+ 1.5 tháng thực tập ngoài doanh nghiệp.

Mọi người có thể xem demo nội dung khóa học tại địa chỉ Video demo khóa học Offline

Các bạn ở xa học không có điều kiện thời gian có thể tham dự khóa Java online để chủ động cho việc học tập. Từ tháng 4/2018, VietJack khuyến mại giá SỐC chỉ còn 250k cho khóa học, các bạn có thể trả lại tiền nếu không hài lòng về chất lượng trong 1 tháng, liên hệ facebook admin fb.com/tuyen.vietjack để thanh toán chuyển khoản hoặc thẻ điện thoại, khóa học bằng Tiếng Việt với gần 100 video, các bạn có thể chủ động bất cứ lúc nào, và xem mãi mãi. Thông tin khóa học tại Khóa học Java Online trên Udemy

Follow fanpage của team //www.facebook.com/vietjackteam/ hoặc facebook cá nhân Nguyễn Thanh Tuyền //www.facebook.com/tuyen.vietjack để tiếp tục theo dõi các loạt bài mới nhất về Java,C,C++,Javascript,HTML,Python,Database,Mobile.... mới nhất của chúng tôi.

[PHP 4, PHP 5, PHP 7, PHP 8]

file_existsChecks whether a file or directory exists

Description

file_exists[string $filename]: bool

Parameters

filename

Path to the file or directory.

On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.

Return Values

Returns true if the file or directory specified by filename exists; false otherwise.

Note:

This function will return false for symlinks pointing to non-existing files.

Note:

The check is done using the real UID/GID instead of the effective one.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Examples

Example #1 Testing whether a file exists

Notes

Note: The results of this function are cached. See clearstatcache[] for more details.

See Also

  • is_readable[] - Tells whether a file exists and is readable
  • is_writable[] - Tells whether the filename is writable
  • is_file[] - Tells whether the filename is a regular file
  • file[] - Reads entire file into an array
  • SplFileInfo

maurice at idify dot nl

14 years ago

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 ;]

welkom at remconijhuis dot nl

8 years ago

I needed to measure performance for a project, so I did a simple test with one million file_exists[] and is_file[] checks. In one scenario, only seven of the files existed. In the second, all files existed. is_file[] needed 3.0 for scenario one and 3.3 seconds for scenario two.  file_exists[] needed 2.8 and 2.9 seconds, respectively. The absolute numbers are off course system-dependant, but it clearly indicates that file_exists[] is faster.

ziptwipi at goioia dot com

6 years ago

Note that realpath[] will return false if the file doesn't exist. So if you're going to absolutize the path and resolve symlinks anyway, you can just check the return value from realpath[] instead of calling file_exists[] first

vernon at kesnerdesigns dot net

15 years ago

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 = '//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;
}

bvazquez at siscomx dot com

15 years ago

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.

jag

3 years ago

file_exists[] does NOT search the php include_path for your file, so don't use it before trying to include or require.

use

    @$result = include $filename;

Yes, include does return false when the file can't be found, but it does also generate a warning. That's why you need the @. Don't try to get around the warning issue by using file_exists[]. That will leave you scratching your head until you figure out or stumble across the fact that file_exists[] DOESN'T SEARCH THE PHP INCLUDE_PATH.

vcoletti at tiscali dot it

5 years ago

With PHP 7.0 on Ubuntu 17.04 and with the option allow_url_fopen=On, file_exists[] returns always false when trying to check a remote file via HTTP.

So
        $url="//www.somewhere.org/index.htm";
        if [file_exists[$url]] echo "Wow!\n";
        else echo "missing\n";

returns always "missing", even for an existing URL.

I found that in the same situation the file[] function can read the remote file, so I changed my routine in

        $url="//www.somewhere.org/index.htm";
        if [false!==file[$url]] echo "Wow!\n";
        else echo "missing\n";

                This is clearly a bit slower, especially if the remote file is big, but it solves this little problem.

ktcb123 at hotmail dot com

14 years ago

For some reason, none of the url_exists[] functions posted here worked for me, so here is my own tweaked version of it.

Fabrizio [staff at bibivu dot com]

16 years ago

here a function to check if a certain URL exist:


in my CMS, I am using it with those lines:

earle dot west at transactionalweb dot com

15 years ago

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.

stuart

14 years ago

When using file_exists, seems you cannot do:



so you must do:



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...

Anonymous

16 years ago

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.

guillermogomezruiz at gmail dot com

15 years ago

I was having problems with the file_exists when using urls, so I made this function:



Cheers!

spark at limao dot com dot br

11 years ago

this code here is in case you want to check if a file exists in another server:



unfortunately the file_exists can't reach remote servers, so I used the fopen function.

dan at sudonames dot com

14 years ago

Here is a simpler version of url_exists:

jaz-t at hotmail dot com

14 years ago

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: //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:
//10.0.0.125/myfile.gif

Steve GS

5 months ago

Wordpress always prepends the full URL to any file it stores in its database so, as noted elsewhere, file_exists[] can't find the file since it uses the 'document root', not the URL.  An easy way out of this is to use:

file_exists [str_replace [home_url[], $_SERVER['DOCUMENT_ROOT'], $file] ]

to check if file $file exists.  Note: As from PHP8, 'DOCUMENT_ROOT' must be enclosed within SQUARE BRACKETS, not braces as suggested by ferodano at gmail dot com

Or, if not using WP, replace home_url[] above with the absolute URL name, eg. '//mywebsite.com' - within quotes and no trailing foreslash.

Avee

14 years ago

I made a bit of code that sees whether a file served via RTSP is there or not:

trevorhawes2 at gmail dot com

1 year ago

NB: This function expects the full server-related pathname to work.

For example, if you run a PHP routine from within, for example, the root folder of your website and and ask:

$bstr = file_exists["/images/Proofreading_patients.jpg"];

You will get FALSE even if that file does exist off root.

You need to add

$bstr = file_exists[__DIR_."/images/Proofreading_patients.jpg"];

to get it to return TRUE - ie : /srv/www/mywebsite.com/public/images/Proofreading_patients.jpg

marufit at gmail dot com

14 years ago

Older php [v4.x] do not work with get_headers[] function. So I made this one and working.

ferodano at gmail dot com

12 years ago

You could use document root to be on the safer side because the function does not take relative paths:



Do not forget to put the slash '/', e.g. my doc root in Ubuntu is /var/www without the slash.

andrewNOSPAMPLEASE at abcd dot NOSPAMERSca

17 years ago

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

17 years ago

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:

Chủ Đề