PHP is_writable() to check if file can be written? - php

I've read that I can use is_writable() to check if a folder or a file is writable.
How do I check if a file can be written to a folder?
Do I check the folder and if the folder is writable? Then the file is allowed to be put into that folder?
What if the file has been written to the folder, how do I check if that is writable again (edited)? Do I need to? If so, do I check the file instead of the folder?
Is it a safe method (correct) to do it?

The PHP function is_writable is exactly for this purpose. If you want to check if file is still writable after you've written the file, you can use the same function.

Read the documentation as linked in the question you pointed to. is_writable() is working on files and directories.
But mind: If you have code like this:
if (is_writeable("foo.txt")) {
$fp = fopen("foo.txt", "w");
/* ...*/
}
This might still fail. For instance there might be a lock or a race condition (permissions change between the two commands). Better simply try to open and then handle the error.
$fp = #fopen("foo.txt", "w");
if (!$fp) {
report_error_in_some_way();
}

Related

How fopen file in Users dir from www dir (wamp)?

I trying to fopen a dir in Users dir ("C:\Users\MYUSERNAME\AppData\Roaming\SOFTWARENAME\")
I trying do that from a php file that located in www dir (wamp folder in C).
This is my try:
$file = fopen('../../../Users/Myusername/AppData/Roaming/SOFTWARENAME/', 'r');
I get "failed to open stream: No such file or directory".
Help?
Thank and sorry for my english.
I think its generally considered a bad idea to try to access files outside of the root directory of the web application and it may even be completely blocked by php unless you turn off a security check.
But that being said, you can try to use an environment variable to get the full path.
Check out this api for example: $_ENV
So your code may look more like this:
$file = fopen($_ENV['HOMEDRIVE'] + $_ENV['HOMEPATH] + '/' + fileName, 'r');
I'm not sure whats in the environment exactly but those are common environment variables on windows.

unlink PHP works when file is in root, not if file is in folder

So this one is pretty straight forward I want to delete a file on the server using PHP, I have:
$myfile = 'theone.png';
unlink($myfile);
This code deletes the file, howevere if the path to file is /images/theone.png, it doesn't work, I have tried images\theone.png with no luck.
If I try and connect with FTP I get the error message to say that cURL does not support the unlink function... Any help would be great.
Thanks Guys!
What about:
$root = realpath($_SERVER['DOCUMENT_ROOT']);
$myfile = '$root/images/theone.png';
unlink($myfile);
Although to my knowledge, your attempted method should work, unless either I'm missing something, or you haven't included some code here that might be interfering with the unlink.
__DIR__ - this magic constant contains current directory, in case that the file is in the same directory as your PHP script you can use:
unlink(__DIR__ . "/$myfile");
If the file is for example in one directory above your PHP script you can use:
unlink(__DIR__ . "/../$myfile");
If the directory has correct access rights it should work.

PHP Unlink Not working

I am trying to delete photo in php using unlink. I have used it earlier on other server but this time it is not working. I have used absolute path for a test but still does not works:
I have used it as:
unlink('img1.jpg');
and :
unlink('http://www.mysite.com/img1.jpg');
Please anyone having such experience?
url not allow in ulink function
can you please used this
It's better, also safety wise to use an absolute path. But you can get this path dynamically.
E.g. using:
getcwd();
Depending on where your PHP script is, your variable could look like this:
$deleteImage = getcwd() . 'img1.jpg';
unlink($deleteImage);
check this
bool unlink ( string $filename [, resource $context ] )
and
filename
Path to the file.
So it only takes a string as filename.
Make sure the file is reachable with the path from the location you execute the script. This is not a problem with absolute paths, but you might have one with relative paths.
Even though unlink() supports URLs (see here) now, http:// is not supported: http wrapper information
use a filesystem path to delete the file.
If you use unlink in a linux or unix you should also check the results of is_writable ( string $filename )
And if the function returns false, you should check the file permissions with fileperms ( string $filename ).
File permissions are usual problems on webspaces, e.g. if you upload an file per ftp with a ftp user, and the webserver is running as an different user.
If this is the problem, you have do to a
chmod o+rwd img1.jpg
or
chmod 777 img1.jpg
to grand write (and delete) permissions for other Users.
unlink($fileName); failed for me.
Then I tried using the realpath($fileName) function as unlink(realpath($fileName)); it worked.
Just posting it, in case if any one finds it useful.
php unlink
use filesystem path,
first define path like this:
define("WEB_ROOT",substr(dirname(__FILE__),0,strlen(dirname(__FILE__))-3));
and check file is exist or not,if exist then unlink the file.
$filename=WEB_ROOT."img1.jpg";
if(file_exists($filename))
{
$img=unlink(WEB_ROOT."img1.jpg");
}
unlink won't work with unlink('http://www.mysite.com/img1.jpg');
use instead
unlink($_SERVER['DOCUMENT_ROOT'].'img1.jpg');//takes the current directory
or,
unlink($_SERVER['DOCUMENT_ROOT'].'dir_name/img1.jpg');
There may be file permission issue.please check for this.
Give relative path from the folder where images are kept to the file where you are writing script.
If file structure is like:
-your php file
-images
-1.jpg
then
unlink(images/1.jpg);
Or there may be some folder permission issue. Your files are on a server or you are running it on localhost? If it is on a server then give 755 permission to the images folder.
you are using url insted of path, here is how you should do it...
i am assuming your are uploading the picture to public_html. i suggest you to create a folder for pictures.
unlink("public_html/img1.jpg");

permission denied - php unlink

I have two files:
b.php and test.txt
<?php
$b = "test.txt";
unlink($b);
?>
and the error is: Warning: unlink(test.txt) [function.unlink]: Permission denied
why? b.php and test.txt is 777 and the same group/login
if I set 777 on the parent directory I can execute unlink but i have to set 777 and back to 755?
You (as in the process that runs b.php, either you through CLI or a webserver) need write access to the directory in which the files are located. You are updating the directory content, so access to the file is not enough.
Note that if you use the PHP chmod() function to set the mode of a file or folder to 777 you should use 0777 to make sure the number is correctly interpreted as an octal number.
You'll first require to close the file using fclose($handle); it's not deleting because the file is in use. So first close the file and then try.
in addition to all the answers that other friends have , if somebody who is looking this post is looking for a way to delete a "Folder" not a "file" , should take care that Folders must delete by php rmdir() function and if u want to delete a "Folder" by unlink() , u will encounter with a wrong Warning message that says "permission denied"
however u can make folders & files by mkdir() but the way u delete folders (rmdir()) is different from the way you delete files(unlink())
eventually as a fact:
in many programming languages, any permission related error may not
directly means an actual permission issue
for example, if you want to readSync a file that doesn't exist with node fs module you will encounter a wrong EPERM error
// Path relative to where the php file is or absolute server path
chdir($FilePath); // Comment this out if you are on the same folder
chown($FileName,465); //Insert an Invalid UserId to set to Nobody Owner; for instance 465
$do = unlink($FileName);
if($do=="1"){
echo "The file was deleted successfully.";
} else { echo "There was an error trying to delete the file."; }
Try this. Hope it helps.
The file permission is okay (0777) but i think your on the shared server, so to delete your file correctly use;
1. create a correct path to your file
// delete from folder
$filename = 'test.txt';
$ifile = '/newy/made/link/uploads/'. $filename; // this is the actual path to the file you want to delete.
unlink($_SERVER['DOCUMENT_ROOT'] .$ifile); // use server document root
// your file will be removed from the folder
That small code will do the magic and remove any selected file you want from any folder provided the actual file path is collect.
In Windows and before PHP version 7.3.0, check that your file has been closed before unlinking it,
as said in https://www.php.net/manual/en/function.unlink.php :
On Windows, it is now possible to unlink() files with handles in use, while formerly that would fail. However, it is still not possible to re-create the unlinked file, until all handles to it have been closed.
As an exemple :
$fullFilePath = 'C:\Users\MyUserName\www\myApp\public\test.txt';
$handle = fopen($fullFilePath , 'w+');
fopen($filePath, 'w+');
fputs($handle, 'Some text in the file');
fclose($handle);
unlink(realpath($insertedLinesFilePath));

How can I determine in PHP if I have write permissions to a folder

I'm writing a WordPress plugin that requires manipulating files in the plugin directory, and I can't figure out how to diagrammatically determine whether PHP has write permissions to a folder. How would I go about achieving this in a relatively simple manner?
$b = is_writable( "/file/or/folder/to/test" ); //boolean value
http://php.net/manual/en/function.is-writable.php
Works on files as well as on folders: "Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable."
fileperms gets permissions for the given file.
Try this function: is_writable()

Categories