How to get permission to use unlink()?

I make a site and it has this feature to upload a file and that file is uploaded to a server

Im just a newbie to php I download xampp and I run this site that i made in my local machine.
My site is like this you upload a file then that file will be uploaded to a server, but when i tried unlink() because when i try to remove the filename to a database I also want to remove that pic on the server, but instead I got an error and it says “Permission denied”.


How can I got permission to use unlink();?

I only run this on my localmachine using xampp

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Permission denied error happens because you’re trying to delete a file without having enough/right permissions for doing that.

To do this you must be using superuser account or be the same user that have uploaded the file.

You can go to the directory from your command line and check the permissions that are set to the file.

The easiest solution is to loggin as administrator/root and delete the file.

Here is another work around:

// define if we under Windows
$tmp = dirname(__FILE__);
if (strpos($tmp, '/', 0)!==false) {
  define('WINDOWS_SERVER', false);
  } else {
  define('WINDOWS_SERVER', true);
  $deleteError = 0;
    if (!unlink($fileName)) {
      $deleteError = 1;
  } else {
    $lines = array();
    exec("DEL /F/Q \"$fileName\"", $lines, $deleteError);
  if ($deleteError) {
    echo 'file delete error';

And some more: PHP Manual, unlink(), Post 106952

I would recommend, always first to check PHP Manual (in case your question concerns PHP), just go to the page with function that you have problems with and just click search CTRL+F in your browser and enter, for example, Windows, and as a result, in your case, you would find at least 7 related posts to that or very close to that what you were looking for.

Solution 2

Read this URL

How to use Unlink() function

I found this information in the comments of the function unlink()

Under Windows System and Apache, denied access to file is an usual error to unlink file. To delete file you must to change file’s owern. An example:


chown($TempDirectory."/".$FileName,666); //Insert an Invalid UserId to set to Nobody Owern; 666 is my standard for "Nobody" 


So try something like this:

$Path = './doc/stuffs/sample.docx';

chown($Path, 666);

if ( unlink($Path) )
    echo "success";
    echo "fail";


Try to use this in the path:


Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply