I am trying to remove an image from a directory using the unlink()
function.
if (file_exists($oldPicture)) {
unlink($oldPicture);
echo 'Deleted old image';
}
else {
echo 'Image file does not exist';
}
The value of $oldPicture
is ../images/50/56/picture.jpg
.
The follow block of code runs without any errors however when I check the directory the image is still there.
Am I doing something wrong here?
Thanks
"@Fred-ii- Yeah everyone is right, I am getting denied permission...any idea how I can fix this? P.S. that error reporting is amazing, it will really help me thanks for that! – BigRabbit"
Use chmod on the file before unlinking it:
if (file_exists($oldPicture)) {
// last resort setting
// chmod($oldPicture, 0777);
chmod($oldPicture, 0644);
unlink($oldPicture);
echo 'Deleted old image';
}
else {
echo 'Image file does not exist';
}
A last resort setting would be using 0777
as in the commented code.
"How would I use var_dump() to check folder/file permissions?"
I.e.: var_dump($oldPicture);
if (file_exists($oldPicture)) {
var_dump($oldPicture);
// last resort setting
// chmod($oldPicture, 0777);
chmod($oldPicture, 0644);
unlink($oldPicture);
echo 'Deleted old image';
}
else {
echo 'Image file does not exist';
}
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.