Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 977
d-c Avatar asked Dec 08 '22 01:12

d-c


1 Answers

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;
}
like image 88
Leigh Bicknell Avatar answered May 18 '23 21:05

Leigh Bicknell