Php check file resource

is_file

Returns true if the filename exists and is a regular file, false otherwise.

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 is_file() example

The above example will output:

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

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

See Also

  • is_dir() — Tells whether the filename is a directory
  • is_link() — Tells whether the filename is a symbolic link
  • SplFileInfo

User Contributed Notes 24 notes

Note that is_file() returns false if the parent directory doesn’t have +x set for you; this make sense, but other functions such as readdir() don’t seem to have this limitation. The end result is that you can loop through a directory’s files but is_file() will always fail.

Читайте также:  Python set exclude set

### Symbolic links are resolved ###

If you pass a symlink (unix symbolic link) as parameter, is_file will resolve the symlink and will give information about the refered file. For example:

is_dir resolves symlinks too.

I tend to use alot of includes, and I found that the is_file is based on the script executed, not ran.
if you request /foo.php and foo.php looks like this:
include( ‘foobar/bar.php’ );
?>
and bar.php looks like this:
echo ( is_file ( ‘foo/bar.txt’ ));
?>

Then PHP (on win32, php 5.x) would look for /foo/bar.txt and not /foobar/foo/bar.txt.
you would have to rewrite the is_file statement for that, or change working directory.
Noting this since I sat with the problem for some time,

here is a workaround for the file size limit. uses bash file testing operator, so it may be changed to test directories etc. (see http://tldp.org/LDP/abs/html/fto.html for possible test operators)

function is_file_lfs ( $path ) exec ( ‘[ -f «‘ . $path . ‘» ]’ , $tmp , $ret );
return $ret == 0 ;
>
?>

if you’re running apache as a service on a win32 machine, an you try to determinate if a file on an other pc in your network exists — ex.: is_file(‘//servername/share/dir1/dir2/file.txt’) — you may return false when you’re running the service as LocalSystem. To avoid this, you have to start the Apache-Service as a ‘registered’ domain user.

is_file doesn’t recognize files whose filenames contain strange characters like czech ů or russian characters in general.

I’ve seen many scripts that take it for granted that a path is a directory when it fails is_file($path). When trying to determine whether a path links to a file or a dir, you should always use is_dir after getting false from is_file($path). For cases like described above, both will fail.

regarding note from rehfeld dot us :

In my experience the best( and easiest ) way to find the extension of a file is :

// use this when you are sure it actually has an extension.
$extension = end ( explode ( «.» , $file_name ));

// this one will also check if it actually has an extension
$parts = explode ( «.» , $file_name );
if ( is_array ( $parts ) && count ( $parts ) > 1 )
$extension = end ( $parts );

sometimes this function does not work because permission ,

you can use this function that check if the path has dot in last will return true .

public function isFile($file) $f = pathinfo($file, PATHINFO_EXTENSION);
return (strlen($f) > 0) ? true : false;
>

you should replace a string between » with your file path to check

It took me a day or so to figure out that is_file() actually looks for a valid $ existing path/file in string form. It is not performing a pattern-like test on the parameter given. Its testing to see if the given parameter leads to a specific existing ‘name.ext’ or other (non-directory) file type object.

Maybe this is a newbie mistake, but note that paths are relative to the filesystem and the location of the script. This means that MS IIS virtual directories are not available by relative path — use an absolute.
This threw me because virtual directories ARE available for URLs, at least on IIS.

be careful, is_file() fails on files larger than your integer storage (2^32 for most).

Warning: is_file(): Stat failed for bigfile (errno=75 — Value too large for defined data type)

In PHP 4.1.0 under win32, this seems to print out a warning message if the file does not exist (using error_reporting = E_ALL & ~E_NOTICE).

This Function deletes everything in a defined Folder:
Works with PHP 4 and 5.

function deletefolder ( $path )
<
if ( $handle = opendir ( $path ))
<
while ( false !==( $file = readdir ( $handle )))
<
if ( $file <> «.» AND $file <> «..» )
<
if ( is_file ( $path . ‘/’ . $file ))
<
@ unlink ( $path . ‘/’ . $file );
>
if ( is_dir ( $path . ‘/’ . $file ))
<
deletefolder ( $path . ‘/’ . $file );
@ rmdir ( $path . ‘/’ . $file );
>
>
>
>
>
?>

I have noticed that using is_file on windows servers (mainly for development) to use a full path c:\ doesn’t always work.

I have had to use
C:/foldertowww/site/file.ext

so I preform an str_replace(‘\\’, ‘/’, $path)
Sometimes I have had the \ instead of / work. (this is using apache2 on XP)

but for sure you cannot have mixed separators.

Note also that if is_file(), (and also is_dir()), will return false if you have the open_basedir configuration set and the file (or directory) is not in one of the configured locations.

Essentially as the other notes offer, if you don’t have permissions to access the file or dir these functions return false but this is also another use case that one may overlook.

In 32 bit environments, these functions including is_file(), stat() filesize() will not work due to PHPs default integer being signed. So anything above ~2.1 billion bytes you actually get a negative value.

This is actually a bug but I dont think there is an easy workaround. Try to switch to 64 bit.

An easy way not to have to choose between hard-coding full paths and using relative paths is either via this line:

// in the bootstrap file
define ( ‘DIR_ROOT’ , dirname ( __FILE__ ));
// in other files, prefix paths with the constant
require( DIR_ROOT . ‘/relative/to/bootstrap.php’ );
?>

or if you have to use a relative path:

require( dirname ( __FILE__ ) . ‘/relative/to/this_file.php’ );
?>

This way all your paths will be absolute, yet you can move the application anywhere in the filesystem.

BTW, each successive call to dirname takes you one step up in the directory tree.

echo __FILE__ ;
// /www/site.com/public/index.php
echo dirname ( __FILE__ );
// /www/site.com/public
echo dirname ( dirname ( __FILE__ ));
// /www/site.com
?>

I see, is_file not work properly on specifical file in /dev (linux)
look :

root@boofh:/data# php -r «var_dump(is_file(‘/dev/core’));»
bool(true)
root@boofh:/data# php -r «var_dump(is_file(‘/proc/kcore’));»
bool(true)

root@boofh:/data# ls -alh /proc/kcore
-r——— 1 root root 128T Aug 13 18:39 /proc/kcore

OR FIND do not detect regular file.
root@boofh:/data# find /dev/ -type f
root@boofh:/data#

// version of php :
root@boofh:/data# php -v
PHP 5.4.4-14+deb7u3 (cli) (built: Jul 17 2013 14:54:08)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies

I do a lot of file parsing and have found the following technique extremely useful:

while (false !== ($document = readdir($my_dir)))
$ext=explode(‘.’,$document);
if($document != ‘.’ && $document != ‘..’ && $ext[1])
‘Do something to file. ‘
>
>

It gets around the fact that, when working on website pages, the html files are read as directories when downloaded. It also allows you to extend the usefulness of the above method by adding the ability to determine file types e.g.

if($document != ‘.’ && $document != ‘..’ && $ext[1]==’htm’)
or
if($document != ‘.’ && $document != ‘..’ && $ext[1]==’doc’)

regarding rlh at d8acom dot com method,

It is incorrect. Well, it works but you are not guaranteed the file extension using that method.

for example : filename.inc.php

your method will tell you the ext is «inc», but it is in fact «php»

heres a way that will work properly.

this is a simple way to find specific files instead of using is_file().
this example is made for mac standards, but easily changed for pc.

function isfile ( $file ) <
return preg_match ( ‘/^[^.^:^?^\-][^:^?]*\.(?i)’ . getexts () . ‘$/’ , $file );
//first character cannot be . : ? — subsequent characters can’t be a : ?
//then a . character and must end with one of your extentions
//getexts() can be replaced with your extentions pattern
>

function getexts () <
//list acceptable file extensions here
return ‘(app|avi|doc|docx|exe|ico|mid|midi|mov|mp3|
mpg|mpeg|pdf|psd|qt|ra|ram|rm|rtf|txt|wav|word|xls)’ ;
>

echo isfile ( ‘/Users/YourUserName/Sites/index.html’ );
?>

Today I got the in the comments already described behaviour that between directory and file can’t be distinguished by is_file() or is_dir().
A dirty and incomplete hack is below, incomplete because it never includes links and I never tested what happens when a directory is not allowed to be read.

it doesn’t work for file over 8Gb. returns false when there actually a file.
it’s probably connected to 32bit integer problem and filesize

Please be aware wildcards do not work as one might expect.

if ( is_file ( $file ) ) echo( $file . ‘ is a regular file’ );
> else echo( $file . ‘ is not a regular file’ );
>
?>

The above snippet suggests that *.* is a regular file. It does not sound regular to me. I would expect is_file() to return FALSE.

Источник

How to check if a file exists from a URL in PHP

Today we’ll explain to you how to check if a file exists from a URL in PHP. Using php built-in file_exists() function, we can check whether a file or directory exists on the server or not but will not use it to check if a file exists on a remote server or not.

Sometimes we need to check the given image URL or another file URL that exists or not so this will help you.

Different ways to check file exists on remote server or not

1. Using fopen() function

Here, we will create a custom function to check if a file exists on a remote server or not using fopen() function in PHP.

2. Using get_headers() function

Also, you can check if the URL is working or not by using the below custom function.

3. Using cURL function

You can do the same task using cURL in PHP as shown in the below code:

That’s it for today.
Thank you for reading. Happy Coding.

You may also like.

Calculate the age from date of birth in PHP - Clue Mediator

Calculate the age from date of birth in PHP

Convert XML to JSON in PHP - Clue Mediator

Convert XML to JSON in PHP

Check Username availability using PHP and jQuery - Clue Mediator

Check username availability using PHP and jQuery

Enable CORS for multiple domains in PHP - Clue Mediator

Enable CORS for multiple domains in PHP

Convert CSV to JSON in PHP - Clue Mediator

Convert CSV to JSON in PHP

Insert an array into a MySQL database using PHP - Clue Mediator

Insert an array into a MySQL database using PHP

Leave a Reply Cancel reply

Search your query

Recent Posts

  • Connect to a MySQL Database Using the MySQL Command: A Comprehensive Guide July 16, 2023
  • Connecting to SSH using a PEM File July 15, 2023
  • How to Add the Body to the Mailto Link July 14, 2023
  • How to Add a Subject Line to the Email Link July 13, 2023
  • How to Create Mail and Phone Links in HTML July 12, 2023

Tags

Join us

Top Posts

Explore the article

We are not simply proficient at writing blog post, we’re excellent at explaining the way of learning which response to developers.

For any inquiries, contact us at [email protected] .

  • We provide the best solution to your problem.
  • We give you an example of each article.
  • Provide an example source code for you to download.
  • We offer live demos where you can play with them.
  • Quick answers to your questions via email or comment.

Clue Mediator © 2023. All Rights Reserved.

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.

Источник

Оцените статью