开发者

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

in php how do I determine whether or n开发者_如何学Goot I can create a file in the same path as the script trying to create a file


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;
}


Have you tries the is_writable() function ?

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

Example:

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


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.


Use is_writable PHP function, documentation and example source code of this you can find at http://pl2.php.net/manual/en/function.is-writable.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜