How to Delete a File in Server PHP VI
PHP includes a number of commands for working with files on the local file system, allowing you to create new files or to copy, move or delete existing files. As well as being useful for Web applications, such as file managers and content management systems, the file commands let server administrators create script files; to automate repetitive jobs, for example. PHP allows you to delete files using the unlink command, which permanently removes files from the server.
Instructions
-
-
1
Open a text editor or Web development application and create a new page.
-
2
Add the following code between the HTML "<body>" "</body>" tags:
<?php
$server_path = $_SERVER['DOCUMENT_ROOT'];
$file_path = $server_path . "/temp/delete-me.txt";
unlink($file_path);
echo "File: " . $file_path . " deleted";
?>First, the server path to the Website is stored in the variable $server_path. The local web path to the file to delete is then added to the server path, to create a full path to the file, which is stored in $file_path. The unlink command is then called, passing the full path of the file to delete, which removes the file. Finally, the code prints a confirmation message to the screen. The user under whom PHP is run must have adequate permissions to delete the requested file; otherwise the unlink command will fail.
-
-
3
Change the $file_path variable to point to an existing file that can be safely deleted. Save the page as delete.php, and upload to your server.
-
4
Open the delete.php page in a Web browser to run the script. You will see the confirmation message, and the chosen file pointed to by $file_path is deleted.
-
1
Tips & Warnings
If you want to delete a temporary file, close the file before running the unlink command, or the unlink command will fail.