Home » Php » security – How to make php script delete itself (and includes dir)

security – How to make php script delete itself (and includes dir)

Posted by: admin July 12, 2020 Leave a comment


How do I make script delete itself after it’ll finish its work?


It’s for my installation script, I want it to delete itself for security reasons (so attacker won’t be able to overwrite existing site).

I forgot to mention that it has its ‘includes’ directory that i would like to be deleted too… Could someone add how to also delete this dir? Includes directory is subdirectory of the same folder where install script is located.

How to&Answers:

You can use unlink to remove a file, and __FILE__ to get the full path to the current file :


As a “proof” :

[email protected]:~/developpement/tests/temp
$ ll | grep 'remove-myself.php'
-rw-r--r-- 1 squale   squale      25 2009-08-01 17:01 remove-myself.php

=> The file exists

[email protected]:~/developpement/tests/temp
$ cat remove-myself.php


=> It contains the code I gave

[email protected]:~/developpement/tests/temp
$ php ./remove-myself.php

=> I launch the script

[email protected]:~/developpement/tests/temp
$ ll | grep 'remove-myself.php'

=> It doesn’t exist anymore

For this to work, you’ll have to be sure you have the required privilegies… this means the user trying to delete the file needs to have right-access on the directory containing it.

When you are in command line, it’s generally OK ; but if you are trying to do this via Apache, you will need to give Apache write-access to that directory/file — Apache doesn’t generally have that kind of privilege by default (not secure, and generally not needed)

Not sure it’d be possible on windows, though… It works on Linux, but Windows might kinda “lock” the file when it’s being executed…


Try unlink. The webserver user will need write permissions for the directory/script.


Side note to other answers:

I would recommend renaming the file, or putting an exit statement in the beginning of the file, removing is IMHO not a good option. The user might want to read your installation script or re-run it. Maybe this could be a better solution:

$contents = file_get_contents(__FILE__);
    "<?php # Remove this line and the next line to re-configure the application
    die('The application has already been configured.'); ?>\n" . $contents

You could as well rename it to something the web server won’t pass to clients, or even better, move it somewhere the web server does not have any access to, or even both:

rename(__FILE__, '/tmp/' . basename(__FILE__) . '.bak');

Don’t forget to mention the place the installation script has been moved to in the installation script, though …

About deleting directories: This is done with rmdir(), the directory must be empty, though. Moving folders is the same as with files, the function is called rename().