Home » Php » Is it possible for a PHP file to delete itself on execution?

Is it possible for a PHP file to delete itself on execution?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have a PHP file “install.php” which handles the installation of other scripts. I want this file to delete itself and its containing folder after it has been run.

Is this possible?

How to&Answers:

A demo given that the folder only contains your install.php:

mkdir demo
cd demo
echo "<?php unlink(__FILE__); rmdir(__DIR__); " > install.php
php install.php
cd ..
ls

The that ls doesn’t show the “demo dir” any more.

The recursive deletion shouldn’t be that hard to figure out ether if there are more (sub-)folders you want to remove.

Answer:

You can use PHP unlink and rmdir command to delete the file (and its folder) itself. Make sure you forward the viewer to other page after you delete the file itself.