Home  >  Article  >  Backend Development  >  PHP determines whether a file is writable

PHP determines whether a file is writable

王林
王林Original
2019-09-30 17:44:243162browse

PHP determines whether a file is writable

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 = &#39;test.txt&#39;;
if (is_writable($filename)) {
    echo &#39;The file is writable&#39;;
} else {
    echo &#39;The file is not writable&#39;;
}
?>

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", &#39;w&#39;)) {
            @fclose($fp);
            @unlink("$dir/test.txt");
            $writeable = 1;
        } else {
            $writeable = 0;
        }
    } else {
        if ($fp = @fopen($file, &#39;a+&#39;)) {
            @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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php determine day of weekNext article:php determine day of week