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));
Related
I am trying to create a temporary directory but I am getting following error
Warning: mkdir(): File exists
However when i checked the directory actually doesn't exist.A typical value for $tmp is /tmp/testKanfEt
$tmp = tempnam(sys_get_temp_dir() , 'test');
echo $tmp;
mkdir($tmp);
What am i missing here ?
The function tempnam() creates a file in given path and returns the full path if created successfully. You are attempting to make a directory with the same path as the file.
But in this case, tempnam() is being used wrongly in my opinion.
It should be used when trying to make tmp files in any other directory than the o.s. tmp folder.
Why? Because making files in the tmp directory you should not care about the file name because once the lock has been released on a file (with fclose() or end of script execution for example) you cannot guarantee the file still being there.
Instead, use tmpfile() as it returns a file handle directly creating a file in the tmp directory.
And if you really need the file name, you still could use tempnam() or retreive it from the handle like so:
echo stream_get_meta_data(($fh=tempfile()))["uri"];
When I try and upload a file as follows:
$name = $img->getClientOriginalName();
$fullPath = Product::getUploadPath(); // Returns public_path(); with custom directory appended
$uploaded = $img->move($fullPath, $name);
I get the below error:
Could not move the file
"/private/var/folders/1l/fxl7spqj2p113fpffm3k0sy00000gn/T/phpIgpWGy" to
"/dir/subdir/subsubdir/subsubdir/public/backend/images/products/pic.jpg" ()
For interestsake, I built the entire resolve path for the image, and passed that as an argument to the move() method. Memory served that it has worked previously.
$uploaded = $img->move($fullPath.'/'.$name);
No exceptions are thrown, however, the uploaded file, now becomes a directory:
"/dir/subdir/subsubdir/subsubdir/public/backend/images/products/pic.jpg/"
I'm very close to driving my fist through my screen.
Could be a permissions issue - the user running the PHP process will need to have write access to the directory where the file will be saved. If you can stomach chmod'ing the directory to 777 for testing, that would at least provide an immediate yes or no to the permissions possibility.
Also, be sure that the directory that file is to be moved to exists - Symfony's UploadedFile::move() method falls back to PHP's move_uploaded_file() function, which according to a comment on the documentation will not create missing directories when moving a file.
When it comes to uploading files, we've all been there before. Can be maddening.
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");
Well my PHP script generated an error with a hyperlink in it.
Does anyone know what's wrong?
PHP Warning: rename(./uploads/temp/00013/,./uploads/orders/39/) [<a href='function.rename'>function.rename</a>]: No such file or directory
update:
actual code in PHP
if(!file_exists('uploads/orders/')) {
mkdir('uploads/orders/'); // ensuring the orders folder exist
}
rename('uploads/temp/' . $u . '/', 'uploads/orders/' . $i . '/');
update:
Sorry, my fault. I coded to delete previous temp folder before this code execute. Thanks!
It seems that one (or both) of these directories don't exist:
uploads/temp/00013
uploads/orders/39
Have you checked that:
these directories exist?
Apache/PHP has permission to read/write in these directories?
Your current directory is really the parent directory of your "upload" directory?
When a computer tells you
No such file or directory
the first thing you should check is if the file/directory exists. This is not a random error message, it's given only in the specific situation when a file or directory you try to use does not exist.
In this case in particular, both ./uploads/temp/00013/ and ./uploads/orders/ have to exist. If orders doesn't exist it's not created for you.
Figured PHP's rename would be my best bet. I didn't see many examples on how to use relative URLs in it though, so I kind of compromised. Either way, this give me permission denied:
I want to do this:
$file = "../data.csv";
rename("$file", "../history/newname.csv");
Where ../ of course would go back 1 directory from where the script is being ran. I couldn't figure out a way...so I did this instead:
$file = "data.csv";
$path = dirname(realpath("../".$file));
rename("$path/$file", "$path/history/newname.csv");
However I am getting permission denied (yes the history folder is owned by www-data, and yes data.csv is owned by www-data). I thought it was weird so I tried a simple test:
rename( 'tempfile.txt', 'tempfile2.txt' );
and I made sure www-data had full control over tempfile.txt...still got permission denied. Why? does the file your renaming it to have to exist? can you not rename like linux's mv? So I instead just copy() and unlink()?
In order to move a file from "../" to "../history/", a process needs write permission to both "../" and "../history/".
In your example, you're obviously lacking write permission to "../". Permissions for the file being moved are not relevant, by the way.
Not only ownership plays a role, but also file permissions. Make sure that the permissions are set up correctly on the source file and destination directory (e.g. chmod 644 data.csv).
Is www-data the same user as Apache?
Edit: Take care to provide existing, absolute paths to realpath(). Also beware of the following:
$path = dirname(realpath("../".$file));
This might yield nothing, because the file ../data.csv might not exist. I.e., the result of realpath() on a non-existent file is false.
Here's some code that might work better for you:
$file = "data.csv";
$path1 = realpath($file);
$path2 = realpath(dirname($file).'/..').'/history/newname.csv';
rename($path1, $path2);
You should be extremely careful that $file cannot be edited by the visitor, because he could change a request manipulate which file is renamed to where.