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
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 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.
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");
}
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.
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.