How to Delete a Poorly Named File in Linux via PHP
Software Development - 2025-08-01
Ever have an experience of developing a PHP site and accidentally create a file that WinSCP or Fillezilla nor any other filemanager is not able to delete? AND, no access to the command line !?
Just means you'll have to do it manually.
I wrote this script to do just that. Because the file name actually was 'C:\\data.csv', the 'C:\\' part was the problem. Those double slashes is what was keeping the FTP filemanagers like WinSCP and FIlezilla from deleting the file.
NOTE: Can be modified to run command lines from PHP. Do not ask me how. This is just for deleting one file.
Although I hope this does not happen to you but if it does, feel free to use this PHP script to help.
The Script:
Copy and Paste the following into a file. Name it 'delete_the_file.php'. Make sure you change the filename before trying to run. Once you're all setup, run the script via your web browser since you don't have command line access. File should delete unless you have some problem other than a bad filename.
<?php
// delete_the_file.php
// Written by Rock Stevens - rockstvens.com
// Using PHP to delete a single (poorly) named file.
// That can not be deleted (because of it's name) via WinSCP, Filezilla or any other filemanager
// And must be done manually, but have no access to the command line.
// The illegally named file... because of the 'C:\\' part,
// is preventing it from being deleted.
$filename = 'C:\\php\\mydata.csv';
// Escape the filename to prevent shell injection
// Not that we are trying to do that, just deleting a File
// But I normally do it this way, escape shell arguments.
$escapedFilename = escapeshellarg($filename);
// Construct the shell command to delete the file
$command = "rm " . $escapedFilename;
// depending on 'where' the file is, and you are a 'sudo'er then...
// maye have to use 'sudo'.
// So, uncomment if needed
// $command = "sudo rm " . $escapedFilename;
// Execute the command
exec($command, $output, $return_code);
// Check for any errors that may have occured
if ($return_code === 0) {
echo "File '$filename' successfully deleted.";
} else {
echo "Error deleting file '$filename':\n";
echo implode("\n", $output); // I do not use implode normally, but cmd line, ok.
}
?>