Php check access to file

PHP File handling Getting file information

The is_dir function returns whether the argument is a directory, while is_file returns whether the argument is a file. Use file_exists to check if it is either.

$dir = "/this/is/a/directory"; $file = "/this/is/a/file.txt"; echo is_dir($dir) ? "$dir is a directory" : "$dir is not a directory", PHP_EOL, is_file($dir) ? "$dir is a file" : "$dir is not a file", PHP_EOL, file_exists($dir) ? "$dir exists" : "$dir doesn't exist", PHP_EOL, is_dir($file) ? "$file is a directory" : "$file is not a directory", PHP_EOL, is_file($file) ? "$file is a file" : "$file is not a file", PHP_EOL, file_exists($file) ? "$file exists" : "$file doesn't exist", PHP_EOL; 
/this/is/a/directory is a directory /this/is/a/directory is not a file /this/is/a/directory exists /this/is/a/file.txt is not a directory /this/is/a/file.txt is a file /this/is/a/file.txt exists 

Checking file type

Use filetype to check the type of a file, which may be:

Passing the filename to the filetype directly:

Note that filetype returns false and triggers an E_WARNING if the file doesn’t exist.

Checking readability and writability

Passing the filename to the is_writable and is_readable functions check whether the file is writable or readable respectively.

The functions return false gracefully if the file does not exist.

Checking file access/modify time

Using filemtime and fileatime returns the timestamp of the last modification or access of the file. The return value is a Unix timestamp — see Working with Dates and Time for details.

echo "File was last modified on " . date("Y-m-d", filemtime("file.txt")); echo "File was last accessed on " . date("Y-m-d", fileatime("file.txt")); 

Get path parts with fileinfo

$fileToAnalyze = ('/var/www/image.png'); $filePathParts = pathinfo($fileToAnalyze); echo '
'; print_r($filePathParts); echo '

';

Array ( [dirname] => /var/www [basename] => image.png [extension] => png [filename] => image ) 
$filePathParts['dirname'] $filePathParts['basename'] $filePathParts['extension'] $filePathParts['filename'] 
  • If an option (the second parameter) is not passed, an associative array is returned otherwise a string is returned.
  • Does not validate that the file exists.
  • Simply parses the string into parts. No validation is done on the file (no mime-type checking, etc.)
  • The extension is simply the last extension of $path The path for the file image.jpg.png would be .png even if it technically a .jpg file. A file without an extension will not return an extension element in the array.

pdf

PDF — Download PHP for free

Источник

is_writable

Возвращает true , если файл filename существует и доступен для записи. Аргумент filename может быть именем директории, что позволяет вам проверять директории на доступность для записи.

Не забывайте, что PHP может обращаться к файлу от имени того пользователя, от которого запущен веб-сервер (обычно ‘nobody’).

Список параметров

Возвращаемые значения

Возвращает true , если filename существует и доступен для записи.

Ошибки

В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .

Примеры

Пример #1 Пример использования is_writable()

$filename = ‘test.txt’ ;
if ( is_writable ( $filename )) echo ‘Файл доступен для записи’ ;
> else echo ‘Файл недоступен для записи’ ;
>
?>

Примечания

Замечание: Результаты этой функции кешируются. Более подробную информацию смотрите в разделе clearstatcache() .

Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обёртками url. Список обёрток, поддерживаемых семейством функций stat() , смотрите в разделе Поддерживаемые протоколы и обёртки.

Смотрите также

  • is_readable() — Определяет существование файла и доступен ли он для чтения
  • file_exists() — Проверяет существование указанного файла или каталога
  • fwrite() — Бинарно-безопасная запись в файл

User Contributed Notes 15 notes

Be warned, that is_writable returns false for non-existent files, although they can be written to the queried path.

To Darek and F Dot: About group permissions, there is this note in the php.ini file:
; By default, Safe Mode does a UID compare check when
; opening files. If you want to relax this to a GID compare,
; then turn on safe_mode_gid.
safe_mode_gid = Off

It appears that is_writable() does not check full permissions of a file to determine whether the current user can write to it. For example, with Apache running as user ‘www’, and a member of the group ‘wheel’, is_writable() returns false on a file like

-rwxrwxr-x root wheel /etc/some.file

Check director is writable recursively. to return true, all of directory contents must be writable

function is_writable_r ( $dir ) if ( is_dir ( $dir )) if( is_writable ( $dir )) $objects = scandir ( $dir );
foreach ( $objects as $object ) if ( $object != «.» && $object != «..» ) if (! is_writable_r ( $dir . «/» . $object )) return false ;
else continue;
>
>
return true ;
>else return false ;
>

>else if( file_exists ( $dir )) return ( is_writable ( $dir ));

This file_write() function will give $filename the write permission before writing $content to it.

Note that many servers do not allow file permissions to be changed by the PHP user.

function file_write ( $filename , & $content ) <
if (! is_writable ( $filename )) if (! chmod ( $filename , 0666 )) echo «Cannot change the mode of file ( $filename )» ;
exit;
>;
>
if (! $fp = @ fopen ( $filename , «w» )) echo «Cannot open file ( $filename )» ;
exit;
>
if ( fwrite ( $fp , $content ) === FALSE ) echo «Cannot write to file ( $filename )» ;
exit;
>
if (! fclose ( $fp )) echo «Cannot close file ( $filename )» ;
exit;
>
>
?>

Regarding you might recognize your files on your web contructed by your PHP-scripts are grouped as NOBODY you can avoid this problem by setting up an FTP-Connection («ftp_connect», «ftp_raw», etc.) and use methods like «ftp_fput» to create these [instead of giving out rights so you can use the usual «unsecure» way]. This will give the files created not the GROUP NOBODY — it will give out the GROUP your FTP-Connection via your FTP-Program uses, too.

Furthermore you might want to hash the password for the FTP-Connection — then check out:
http://dev.mysql.com/doc/mysql/en/Password_hashing.html

The results of this function seems to be not cached :
Tested on linux and windows

chmod ( $s_pathFichier , 0400 );
echo ‘

' ; var_dump ( is_writable ( $s_pathFichier ));echo '

‘ ;
chmod ( $s_pathFichier , 04600 );
echo ‘

' ; var_dump ( is_writable ( $s_pathFichier ));echo '

‘ ;
exit;
?>

This function returns always false on windows, when you check an network drive.

We have two servers: one running PHP 5.0.4 and Apache 1.3.33, the other running PHP 4.3.5 and Apache 1.3.27. The PHP 4 server exhibits the behavior you are describing, with is_writable() returning ‘false’ even though the www user is in the group that owns the file, but the PHP 5 server is returning ‘true.’

This is the latest version of is__writable() I could come up with.
It can accept files or folders, but folders should end with a trailing slash! The function attempts to actually write a file, so it will correctly return true when a file/folder can be written to when the user has ACL write access to it.

function is__writable ( $path ) //will work in despite of Windows ACLs bug
//NOTE: use a trailing slash for folders.
//see http://bugs.php.net/bug.php?id=27609
//see http://bugs.php.net/bug.php?id=30931

if ( $path < strlen ( $path )- 1 >== ‘/’ ) // recursively return a temporary file path
return is__writable ( $path . uniqid ( mt_rand ()). ‘.tmp’ );
else if ( is_dir ( $path ))
return is__writable ( $path . ‘/’ . uniqid ( mt_rand ()). ‘.tmp’ );
// check tmp file for read/write capabilities
$rm = file_exists ( $path );
$f = @ fopen ( $path , ‘a’ );
if ( $f === false )
return false ;
fclose ( $f );
if (! $rm )
unlink ( $path );
return true ;
>
?>

Since looks like the Windows ACLs bug «wont fix» (see http://bugs.php.net/bug.php?id=27609) I propose this alternative function:

function is__writable ( $path )

if ( $path < strlen ( $path )- 1 >== ‘/’ )
return is__writable ( $path . uniqid ( mt_rand ()). ‘.tmp’ );

if ( file_exists ( $path )) if (!( $f = @ fopen ( $path , ‘r+’ )))
return false ;
fclose ( $f );
return true ;
>

if (!( $f = @ fopen ( $path , ‘w’ )))
return false ;
fclose ( $f );
unlink ( $path );
return true ;
>

?>

It should work both on *nix and Windows

NOTE: you must use a trailing slash to identify a directory

function is_writable(‘ftp://user. ‘) always return false. I can create/delete files, but can check is writable. Is this bug or php feature :)?

I’d like to also clarify a point on this. Even if you see 777 permissions for the directly, you may need to check your ACL, since your server’s group might not have write permissions there.

Check if a directory is writable. Work also on mounted SMB shares:

Источник

How to Check if a File Exists in PHP

Monty Shokeen

Monty Shokeen Last updated Jul 21, 2021

Many times you will either need to move files around or store some data inside them in PHP. In either case, knowing beforehand whether a file exists or not can help us avoid some unexpected behavior.

PHP comes with a variety of functions to handle different types of queries related to files. In this tutorial, I’ll give you a brief overview of all these functions so that you can pick one that works best in your situation.

The Importance of Checking if a File Exists

There are a lot of scenarios in which checking if a file exists before doing anything else could be important. Let’s say your website allows users to upload image files on your server that they can access later. It’s fair to assume that there is always a chance of a clashing file name if many users are using your service to upload multiple files frequently.

In such cases, it becomes important to check if there is already another file at the location where you want to save the recently uploaded file of a user. You will then have the option to take some steps like renaming the file to something else or letting the user know that their upload will overwrite an existing file.

Let’s consider another situation where you are supposed to be appending data to a file in PHP. If the file you created to write all your data is deleted for some reason, functions like file_put_contents() will just create a new file with the specified name and store your data inside the newly created file. This might be desirable in some situations, but that won’t always be the case. So it makes sense to check if the file exists beforehand if you already expect it to be there before you begin writing your data.

Checking if a File Exists in PHP

There are three different functions that you can use to check if a file exists in PHP.

The first function is file_exists() . This function accepts a single parameter that is the path where your file is located. Keep in mind that it will return true for both existing files and directories. This may or may not be sufficient for your needs.

You can consider using the is_file() function if you want to be sure that the path you specified points to a file and not a directory. Similarly, you can use the is_dir() function to check if the path you specified exists and if it points to a directory.

Источник

Читайте также:  Php у book free
Оцените статью