简体   繁体   中英

How do I check if I have write permissions in the current path

在php中我如何确定是否可以在与尝试创建文件的脚本相同的路径中创建文件

Have you tries the is_writable() function ?

http://www.php.net/manual/en/function.is-writable.php http://www.php.net/manual/en/function.is-writable.php

$filename = 'test.txt';
if (is_writable($filename)) {
    echo 'The file is writable';
} else {
    echo 'The file is not writable';
}

Unfortunately, all of the answers so far are wrong or incomplete.

is_writable

Returns TRUE if the filename exists and is writable

This means that:

is_writable(__DIR__.'/file.txt');

Will return false even if the script has write permissions to the directory, this is because file.txt does not yet exist.

Assuming the file does not yet exist, the correct answer is simply:

is_writable(__DIR__);

Here's a real world example, containing logic that works whether or not the file already exists:

function isFileWritable($path)
{
    $writable_file = (file_exists($path) && is_writable($path));
    $writable_directory = (!file_exists($path) && is_writable(dirname($path)));

    if ($writable_file || $writable_directory) {
        return true;
    }
    return false;
}

The is_writable function is good stuff. However, the OP asked about creating a file in the same directory as the script. Blatantly stealing from vlad b, do this:

$filename = __DIR__ . '/test.txt';
if (is_writable($filename)) {
    echo 'The file is writable';
} else {
    echo 'The file is not writable';
}

See the php manual for predefined constants for the details on __DIR__ . Without it, you're going to create a file in the current working directory, which is probably more or less undefined for your purposes.

使用is_writable PHP函数,文档和示例源代码,您可以在http://pl2.php.net/manual/en/function.is-writable.php找到

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM