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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With