I'm frustrated about deleting file in ubuntu using PHP unlink().
I created a very simple simulation as follow:
create a folder named "files" beneath /var/www with 766 permission.
upload a file, let say "image.png" in that folder & set the permission into 666
create a php file named delete.php, set the permission to 644 and upload to /var/www directory
Call the file in browser (I use localhost)
The "image.png" still exists in "files" directory
Here is the php script of delete.php :
$filename = 'image.png';
$file = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR . $filename;
unlink($file);
I also tried the following script :
$filename = 'image.png';
$dir = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'files';
chdir($dir);
unlink($filename);
But still can't delete the file.
Unlink throws a warning on failure. Check if E_WARNING is visible for you to find out whats going on.
It usually boils down to user rights. Keep in mind if your script is executed by a browser, usually a user named wwwrun or wwwdata (or something similar) is executing it on your server.
Check if this user has permissions to delete, then try again.
The folder/owner of the directory could be a different user than the user being used to run php.
You should create a folder with the user php assigned. If you cannot do that yourself ask your ISP to do it. That is how I solved a similar problem.
One user cannot delete files of another user on a unix system.
If you would set it to 777 then you could delete it...
Related
I try to move a temporary file located in the /tmp dir to another dir somewhere else on the server using the rename() function. But I get an error:
Permission denied (Code: 2)
for the temporary file. How can I move a temporary file to another location? If I check that the file exists with file_exists() I get true. And if I copy() the temporary file it works fine.
Here's my code so far:
$toPath = '/var/www/htdocs/myproject/some/file.pdf'
$fileName = 'myfile.pdf';
$filePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $fileName;
rename($filePath, $toPath); // Permission denied (Code: 2) here
this is caused by sticky bit set on the directory:
drwxrwxrwt. 8 root root 4096 Feb 6 09:38 .
sticky bit basically stops non-owners of file to rename or delete the file. It is usually set on /tmp and similar directories where multiple users have write permissions and/or save temporary files in, in order to prevent accidental deletion.
For more info, see: https://www.thegeekstuff.com/2013/02/sticky-bit/
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));
I recently started to mess around with some HTML and PHP, and have run into what is probably a super easy to solve error, but one I have not for the life of me been able to fix.
In a nutshell, what I'm trying to do is create a directory, then create a .txt file in that directory with the same name, something to the effect of "/number/number.txt". While it seems simple to create a file, or to create a directory, I'm having no end of troubles trying to do both.
Here's my code:
mkdir($postnum, 0777);
chmod($postnum, 0777);
$post = "/" . $postnum . "/" . $postnum . ".txt";
$post = boards(__FILE__) . $post;
$po = fopen($post, 'w+') or die("Can't open file");
chmod($post, 0777);
A few issues I ran into writing this, I read that using mkdir I could set the permissions of the directory I create, but despite doing what I believe to be the right way of doing so, it didn't do anything. So I ran chmod right after.
Then, I had hoped that just /$postnum/$postnum.txt would work for the directory to open, but I get the die text when I try just that, I had to add in the "boards(FILE) part to get it to work. (Side note, "boards" is the directory I'm working in)
Even then, while it doesn't give me "Can't open file", it isn't creating the file or anything.
I've made certain that any file or folder even remotely interacting with the files has had it's permissions set to 0777, so it's likely not an issue with that. (Also, I know that having all my files completely open like that may not be the best idea; once I get this working properly, I'll be sure to set the permissions to something more safe)
Any idea what I'm doing wrong?
making directory and creating path:-
$new_folder=mkdir('uploads\\'.$folder_name, 0777, true);
('uploads\\'.$folder_name)->path where you create folder like www->upload->folder name(whatever you provide)
$path="uploads\\".$folder_name."\\";//if you want to provide path you can provide this way
The mkdir function takes a path relative to the root of the filesystem, not the document root.
If you're on a *nix system, your website document root is likely in a path such as /var/www/sitename/html, but you're trying to create /number/number.txt which your account doesn't have permissions to do. Change the path you pass into mkdir to somewhere in the filesystem you have permissions to create folders and files and your code should work.
Edit:
The code in your question doesn't actually attempt to write anything. By calling fopen you've created a file handle, but you need to call fwrite to actually write data to the file. As suggested by #JamesSwift, you may want to take a look at file_put_contents.
Here, try this :
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
mkdir("$root/root_website_folder/php/testing_folder", 0777);
PHP uses your real path not the virtual one, we assign to $root the real path on your machine than add the virtual path of your website root
I have a really simple PHP script that creates a directory according to a product id, these folders are made to upload product id specific images into it.
Once this folder is made with PHP script mkdir('folder',0777) I upload an image with PHP to that just made folder. This doesn't work as it should : the move_uploaded_file function returns a regulation in the server safe_mode function. Although this the servers safe_modeproperty is turned off, is still gives this error / warning.
When I check with my FTP user account, I see the made directory with permission 777, but the uploads won't succees to upload to that directory...
Strangeness of it is that when i manually delete the made directory and make a new one (via FTP) the uploads work perfect!
Does anyone have any clue on fixing this issue? I'm not that server experienced :)
Thanks!
use this for mkdir username is your foldername in uplod folder
if(!is_dir('uploads/'.$username . "/")) {
mkdir('uploads/'.$username . "/", 0755);
}`
You have to take in account, that when creating a directory the create mask is anded with the umask:
$old = umask( 0 );
mkdir( 'folder', 0777, true );
umask( $old );
The mode on your directory may be being affected by your current umask. It will end
up having (mkdir-mode & (~umask)) permissions.
Try:
$oldmask = umask(0);
mkdir('folder', 0777);
umask($oldmask);
I'm using this PHP code below to create dynamic xml files.
...
$file_name = "";
$rss_feed_dir = $_SERVER['DOCUMENT_ROOT'] . '/xml/';
chmod($rss_feed_dir, 0777);
$file = $rss_feed_dir . $file_name . '.xml';
$file_handle = fopen($file, "w");
fwrite($file_handle, $xml);
fclose($file_handle);
The file will be created if the directory permissions are set 0777, and seems to fail at 0755. I've read on many sites that world execute permissions can pose a security risk.
Should I chmod back to 0755 at the end of this script?
Is there a better way to set the directory permissions?
I suspect it is because whichever directory your rss_feed_dir points to, is a directory owned by another user - other than the user that is being used to run your script.
So 755 permissions would exclude you from write access to the directory if your script is not running with the specified group or user. Which explains why you cannot do a write file command successfully when permissions were 755, but successful when 777.
If this php file is on a server and being called from the web, try modifying your directory ownership itself:
chown -R YOUR_USER:www-data YOUR_RSS_DIRECTORY_HERE
And then chmod to 775
Hope that helps!