How to Use PHP’s is_writable() to Check File and Directory Permissions
This guide explains PHP’s is_writable() function, its syntax, and how to use it to check whether files or directories are writable, including examples for checking file writability, directory writability, existence, and permission handling, helping developers manage file system operations safely.
is_writable() function syntax
bool is_writable ( string $filename )The $filename parameter 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 returns true if the specified file exists and is writable, otherwise false. Example:
$filename = 'example.txt';
if (is_writable($filename)) {
echo '文件可写';
} else {
echo '文件不可写';
}Check if a directory is writable
The same function can verify directory writability. Example:
$directory = 'example';
if (is_writable($directory)) {
echo '目录可写';
} else {
echo '目录不可写';
}Check if a file exists and is writable
Combine file_exists() with is_writable() to first ensure the file exists, then test writability. Example:
$filename = 'example.txt';
if (file_exists($filename)) {
if (is_writable($filename)) {
echo '文件存在且可写';
} else {
echo '文件存在但不可写';
}
} else {
echo '文件不存在';
}Check write permission of a file or directory
The function also indicates whether the target has write permission. Example:
$filename = 'example.txt';
if (is_writable($filename)) {
echo '文件或目录具有可写的权限';
} else {
echo '文件或目录不具有可写的权限';
}Summary
The is_writable() function is a useful tool for determining whether a file or directory is writable. By passing the path to the target, developers can quickly assess write permissions and handle file system operations accordingly.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
