How do I make script delete itself after it'll finish its work?
edit:
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.
The rmdir() function in PHP is an inbuilt function which is used to remove an empty directory. It is mandatory for the directory to be empty, and it must have the relevant permissions which are required to delete the directory.
The unlink() function is an inbuilt function in PHP which is used to delete files. It is similar to UNIX unlink() function. The $filename is sent as a parameter that needs to be deleted and the function returns True on success and false on failure.
To delete a file in PHP, use the unlink function. Let's go through an example to see how it works. The first argument of the unlink function is a filename which you want to delete. The unlink function returns either TRUE or FALSE , depending on whether the delete operation was successful.
You can use unlink
to remove a file, and __FILE__
to get the full path to the current file :
unlink(__FILE__);
As a "proof" :
squale@shark:~/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
squale@shark:~/developpement/tests/temp
$ cat remove-myself.php
<?php
unlink(__FILE__);
=> It contains the code I gave
squale@shark:~/developpement/tests/temp
$ php ./remove-myself.php
=> I launch the script
squale@shark:~/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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With