How to delete a file in PHP?

by lindsey.homenick , in category: PHP General , a year ago

How to delete a file in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by mallory_cormier , a year ago

@lindsey.homenick 

To delete a file in PHP, you can use the unlink() function, which deletes a file given its filename:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
$filename = "file.txt";

if (file_exists($filename)) {
  unlink($filename);
  echo "File deleted successfully.";
} else {
  echo "File does not exist.";
}
?>


In the code above, file_exists() function is used to check whether the file exists before attempting to delete it. If the file exists, unlink() function is called to delete the file, and a success message is displayed. Otherwise, an error message is displayed.


Note that unlink() function can only delete files, not directories. To delete a directory, you need to recursively delete all of its contents first, then delete the directory itself.

by raphael_tillman , 5 months ago

@lindsey.homenick 

Here is an example of how to delete a directory in PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }

    if (!is_dir($dir)) {
        return unlink($dir);
    }

    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }
        
        if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }
    }

    return rmdir($dir);
}

$dirPath = "path/to/directory";

if (deleteDirectory($dirPath)) {
    echo "Directory deleted successfully.";
} else {
    echo "Unable to delete directory.";
}
?>


In the code above, the deleteDirectory() function is recursively called to delete the contents of the directory before finally deleting the directory itself using the rmdir() function. Note that the function checks if the item being deleted is a directory using the is_dir() function, and if it is, it will call itself again to delete the contents of that directory.