d-c
d-c

Reputation: 249

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

in php how do I determine whether or not I can create a file in the same path as the script trying to create a file

Upvotes: 5

Views: 8371

Answers (4)

Leigh Bicknell
Leigh Bicknell

Reputation: 872

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

Upvotes: 9

easel
easel

Reputation: 4048

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.

Upvotes: 2

Svisstack
Svisstack

Reputation: 16616

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

Upvotes: 0

vlad b.
vlad b.

Reputation: 695

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

Upvotes: 5

Related Questions