Using PHP is_writable() to Check File and Directory Write Permissions
This article explains the PHP is_writable() function, its syntax, and provides multiple examples showing how to check write permissions for files and directories, as well as how to combine it with file existence checks and permission verification.
is_writable() Function Syntax
<code>bool is_writable ( string $filename )</code>$filename is the path of the file or directory to be checked.
Usage of is_writable()
Check if a file is writable
The is_writable() function can be used to determine whether a specified file is writable. If the file exists and is writable, it returns true; otherwise, it returns false. Example:
<code>$filename = 'example.txt';
if (is_writable($filename)) {
echo '文件可写';
} else {
echo '文件不可写';
}</code>In this example, a variable $filename stores the path of the file to be checked, and is_writable() determines its writability, outputting the appropriate message.
Check if a directory is writable
The same function also works for directories. If the directory exists and is writable, it returns true; otherwise, false. Example:
<code>$directory = 'example';
if (is_writable($directory)) {
echo '目录可写';
} else {
echo '目录不可写';
}</code>Here, $directory holds the directory path, and is_writable() checks its write permission.
Check if a file exists and is writable
The function can be combined with file_exists() to first verify a file's existence and then its writability. Example:
<code>$filename = 'example.txt';
if (file_exists($filename)) {
if (is_writable($filename)) {
echo '文件存在且可写';
} else {
echo '文件存在但不可写';
}
} else {
echo '文件不存在';
}</code>This code first checks for the file's existence; if it exists, it then checks whether it is writable.
Check write permissions of a file or directory
is_writable() can also be used directly to test whether a file or directory has write permissions. Example:
<code>$filename = 'example.txt';
if (is_writable($filename)) {
echo '文件或目录具有可写的权限';
} else {
echo '文件或目录不具有可写的权限';
}</code>The function returns true when the target has write permission and false otherwise.
Summary
The is_writable() function is a useful tool for checking whether a file or directory is writable. By passing the path of the target to the function, developers can quickly determine write accessibility and handle the result accordingly.
PHP Learning Recommendations
Vue3+Laravel8+Uniapp小白到实战开发教程
Vue3+TP6+API 社交电商系统开发教学
swoole从入门到精通推荐课程
《Workerman+TP6即时通讯聊天系统》限时秒杀!
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.