0

I am not able to delete the files from a folder using php whenever the user clicks yes to delete form submission. The files are still present in the folder even after using unlink() function:

<form method='post'>
<input type='submit' name='del' value='Yes'>
</form>
<?php
if(isset($_POST['del']))
    {

     $filename=$userid.".jpg";
     unlink('upload-cover/uploads/$userid/$filename');
     echo "Your image has been deleted successfully!!";
    }

?>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
gapc311
  • 463
  • 2
  • 6
  • 15
  • 1
    Learn basic PHP syntax: variables are expanded inside double quotes, not inside single quotes. – Barmar Feb 22 '14 at 09:51

3 Answers3

2

You have to have the string passed to the unlink function in double-quotes. This is because PHP will interpret strings in single-quotes literally, therefore not including your variables. Try this:

unlink("upload-cover/uploads/$userid/$filename");

Or:

unlink("upload-cover/uploads/".$userid."/".$filename);

I think the second option is a lot more readable, and prevents errors like the one you encountered!

This is a great answer to understand PHP strings and paths: What is the difference between single-quoted and double-quoted strings in PHP?

Community
  • 1
  • 1
Patrick Geyer
  • 1,515
  • 13
  • 30
1

If you use single quotes, the file name genrated will be incorrect.

Also, make sure you have right permissions

Try with

 unlink("upload-cover/uploads/$userid/$filename");
cornelb
  • 6,046
  • 3
  • 19
  • 30
0

By looking into your code it seems that it is variable look up problem

variable inside single quotes are string to the php engine

unlink('upload-cover/uploads/$userid/$filename');

where as variable inside double quotes are variable to the php engine

unlink("upload-cover/uploads/$userid/$filename");
CS GO
  • 914
  • 6
  • 20