PHP determines whether a file or directory is writable
In PHP, the is_writable() function can be used to determine whether a file/directory is writable. , details are as follows:
Reference
is_writable
— Determine whether the given file name is writable.
Description
bool is_writable (string $filename)
Returns TRUE if the file exists and is writable. (The $filename parameter can be a directory name, that is, check whether the directory is writable.)
Note:
PHP may only be able to run the webserver as the username (usually as 'nobody') to access files, does not count against safe mode restrictions.
is_writable() Example
<?php $filename = 'test.txt'; if (is_writable($filename)) { echo 'The file is writable'; } else { echo 'The file is not writable'; } ?>
Note: is_writeable() is an alias of is_writable()!
In order to be compatible with various operating systems, you can customize a writable function. The code is as follows:
/** * 判断 文件/目录 是否可写(取代系统自带的 is_writeable 函数) * * @param string $file 文件/目录 * @return boolean */ function new_is_writeable($file) { if (is_dir($file)){ $dir = $file; if ($fp = @fopen("$dir/test.txt", 'w')) { @fclose($fp); @unlink("$dir/test.txt"); $writeable = 1; } else { $writeable = 0; } } else { if ($fp = @fopen($file, 'a+')) { @fclose($fp); $writeable = 1; } else { $writeable = 0; } } return $writeable; }
Recommended tutorial: PHP video tutorial
The above is the detailed content of PHP determines whether a file is writable. For more information, please follow other related articles on the PHP Chinese website!