Bootstrap FreeKB - PHP - Delete a file using unlink
PHP - Delete a file using unlink

Updated:   |  PHP articles

unlink can be used to delete a file in PHP.

PHP is typically being run as the apache or www-data user, thus the apache or www-data user will need to have permission to delete the file. exec can be used to run the whoami command to determine if PHP is being run as apache or www-data.

<?php
  echo exec('whoami');
?>

 

And getcwd will return your present working directory.

<?php
  echo getcwd();
?>

 

For example, let's say you want to delete the /var/www/html/foo.php file on a Linux system. In this example, the www-data user has rwx (read, write, execute) permissions to the foo.php, so the www-data user should be able to delete the the foo.php file.

~]$ ls -ld /var/www/html
drwxr-xr-x. 2 www-data  www-data  6 Feb  5 07:59 /var/www/html

 

Here is how you would delete the /var/www/html/foo.php file.

unlink("/var/www/html/foo.php");

 

It's probably also a good idea to use file_exists to determine if the file exists.

$file = ""/var/www/html/foo.php";

if (file_exists($file)) {
  if (unlink($file)) {
    echo "successfully deleted $file <br />";
  }
  else {
    echo "failed to delete $file <br />";
  }
}



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 72fdf0 in the box below so that we can be sure you are a human.