Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make php script delete itself (and includes dir) [duplicate]

Tags:

security

php

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.

like image 656
Phil Avatar asked Aug 01 '09 14:08

Phil


People also ask

How to delete a dir in PHP?

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.

How to use unlink function in PHP?

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.

How to remove file with PHP?

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.


2 Answers

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...

like image 152
Pascal MARTIN Avatar answered Nov 15 '22 21:11

Pascal MARTIN


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

like image 42
Glass Robot Avatar answered Nov 15 '22 21:11

Glass Robot