Php check if can write file

How do I check if a directory is writeable in PHP?

Syntax: Returns if the file or directory specified by filename exists; otherwise. will return false if the file doesn’t already exist in the directory.

Check if file exists in php

if (!(file_exists(http://mysite.com/images/thumbnail_1286954822.jpg)))
if (!file_exists('http://example.com/images/thumbnail_1286954822.jpg'))

file_exists checks whether a file exist in the specified path or not.

file_exists ( string $filename ) 

Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.

$filename = BASE_DIR."images/a/test.jpg"; if (file_exists($filename))< echo "File exist."; >else

Another alternative method you can use getimagesize(), it will return 0(zero) if file/directory is not available in the specified path.

Based on your comment to Haim, is this a file on your own server? If so, you need to use the file system path, not url (e.g. file_exists( ‘/path/to/images/thumbnail.jpg’ ) ).

How to check if a directory or a file exists in system or, In the below example we are checking if /usr/games directory is present or not. #!/bin/bash. if [ -d /usr/games ]; then. echo «The Directory Exists». else. echo «The Directory is not present». fi. Let’s see another example where we have deleted a file from the directory and let’s check what happens.

Читайте также:  Github java api examples

How do I check if a directory is writeable in PHP?

Does anyone know how I can Check to see if a directory is writeable in PHP?

The function is_writable doesn’t work for folders.

Edit: It does work. See the accepted answer.

Yes, it does work for folders.

Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable.

to be more specific for owner/group/world

$dir_writable = substr(sprintf('%o', fileperms($folder)), -4) == "0774" ? "true" : "false"; 

You may be sending a complete file path to the is_writable() function. is_writable() will return false if the file doesn’t already exist in the directory. You need to check the directory itself with the filename removed, if this is the case. If you do that, is_writable will correctly tell you whether the directory is writable or not. If $file contains your file path do this:

$file_directory = dirname($file); 

Then use is_writable($file_directory) to determine if the folder is writable.

I hope this helps someone.

Php check if parameter exists Code Example, Dart answers related to “php check if parameter exists” check directory exists in php; check file selected in php; check if cookie exists php; check if session variable exists php; check if table exists sql php; how to check user already exists in php; if don’t exist key json php; if exist php; laravel check if session variable exists; php

How can I use PHP to check if a directory is empty?

I am using the following script to read a directory. If there is no file in the directory it should say empty. The problem is, it just keeps saying the directory is empty even though there ARE files inside and vice versa .

It seems that you need scandir instead of glob, as glob can’t see unix hidden files .

else < echo "the folder is NOT empty"; >function is_dir_empty($dir) < if (!is_readable($dir)) return null; return (count(scandir($dir)) == 2); >?> 

Note that this code is not the summit of efficiency, as it’s unnecessary to read all the files only to tell if directory is empty. So, the better version would be

function dir_is_empty($dir) < $handle = opendir($dir); while (false !== ($entry = readdir($handle))) < if ($entry != "." && $entry != "..") < closedir($handle); return false; >> closedir($handle); return true; > 

By the way, do not use words to substitute boolean values. The very purpose of the latter is to tell you if something empty or not. An

expression already returns Empty or Non Empty in terms of programming language, false or true respectively — so, you can use the very result in control structures like IF() without any intermediate values

I think using the FilesystemIterator should be the fastest and easiest way:

// PHP 5 >= 5.3.0 $iterator = new \FilesystemIterator($dir); $isDirEmpty = !$iterator->valid(); 

Or using class member access on instantiation:

// PHP 5 >= 5.4.0 $isDirEmpty = !(new \FilesystemIterator($dir))->valid(); 

This works because a new FilesystemIterator will initially point to the first file in the folder — if there are no files in the folder, valid() will return false . (see documentation here.)

As pointed out by abdulmanov.ilmir, optionally check if the directory exists before using the FileSystemIterator because otherwise it’ll throw an UnexpectedValueException .

How to Create a Folder if It Doesn’t Exist in PHP, Methods: file_exists(): It is an inbuilt function that is used to check whether a file or directory exists or not. is_dir(): It is also used to check whether a file or directory exists or not. mkdir() : This function creates a directory. Method 1: Using file_exists() function: The file_exists() function is used to check whether a …

How to Create a Folder if It Doesn’t Exist in PHP ?

We can easily create a folder in PHP, but before that, you have to check if the folder or directory already exists or not. So In this article, you will learn both to Check and Create a folder or directory in PHP.

  1. file_exists(): It is an inbuilt function that is used to check whether a file or directory exists or not.
  2. is_dir(): It is also used to check whether a file or directory exists or not.
  3. mkdir() : This function creates a directory.

Method 1: Using file_exists() function: The file_exists() function is used to check whether a file or directory exists or not.

Parameters: The file_exists () function in PHP accepts only one parameter $path . It specifies the path of the file or directory you want to check.

Return Value: It returns True on success and false on failure.

Источник

is_writable

Returns true if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often ‘nobody’).

Parameters

The filename being checked.

Return Values

Returns true if the filename exists and is writable.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Examples

Example #1 is_writable() example

$filename = ‘test.txt’ ;
if ( is_writable ( $filename )) echo ‘The file is writable’ ;
> else echo ‘The file is not writable’ ;
>
?>

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_readable() — Tells whether a file exists and is readable
  • file_exists() — Checks whether a file or directory exists
  • fwrite() — Binary-safe file write

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:

Источник

is_writable

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

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

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

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

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

Примеры

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

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

Ошибки

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

Примечания

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

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

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

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

Источник

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