Hapus file dengan php

Misalnya saya punya folder bernama `Temp 'dan saya ingin menghapus atau menyiram semua file dari folder ini menggunakan PHP. Bisakah saya melakukan ini?

$files = glob('path/to/temp/*'); // get all file names
foreach($files as $file){ // iterate files
  if(is_file($file))
    unlink($file); // delete file
}

Jika Anda ingin menghapus file 'tersembunyi' seperti .htaccess, Anda harus menggunakannya

$files = glob('path/to/temp/{,.}*', GLOB_BRACE);

Jika Anda ingin menghapus semuanya dari folder (termasuk subfolder) gunakan kombinasi array_map ini, unlink dan glob:

array_map('unlink', glob("path/to/temp/*"));

Perbarui

Panggilan ini juga dapat menangani direktori kosong - terima kasih atas tipnya, @mojuba!

array_map('unlink', array_filter((array) glob("path/to/temp/*")));

Berikut adalah pendekatan yang lebih modern menggunakan Standard PHP Library (SPL) .

$dir = "path/to/directory";
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
    $file->isDir() ?  rmdir($file) : unlink($file);
}
return true;

foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
    if(!$fileInfo->isDot()) {
        unlink($fileInfo->getPathname());
    }
}

Kode ini dari http://php.net/unlink :

/**
 * Delete a file or recursively delete a directory
 *
 * @param string $str Path to file or directory
 */
function recursiveDelete($str) {
    if (is_file($str)) {
        return @unlink($str);
    }
    elseif (is_dir($str)) {
        $scan = glob(rtrim($str,'/').'/*');
        foreach($scan as $index=>$path) {
            recursiveDelete($path);
        }
        return @rmdir($str);
    }
}

$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
    unlink($v);
}

Lihat readdir dan batalkan tautan .

<?php
    if ($handle = opendir('/path/to/files'))
    {
        echo "Directory handle: $handle\n";
        echo "Files:\n";

        while (false !== ($file = readdir($handle)))
        {
            if( is_file($file) )
            {
                unlink($file);
            }
        }
        closedir($handle);
    }
?>

Dengan asumsi Anda memiliki folder dengan BANYAK file membaca semuanya dan kemudian menghapus dalam dua langkah tidak berkinerja . Saya percaya cara paling berkinerja untuk menghapus file adalah dengan hanya menggunakan perintah sistem. 

Sebagai contoh di linux saya menggunakan:

exec('rm -f '. $absolutePathToFolder .'*');

Atau ini jika Anda ingin penghapusan rekursif tanpa perlu menulis fungsi rekursif

exec('rm -f -r '. $absolutePathToFolder .'*');

perintah persis yang sama ada untuk OS apa pun yang didukung oleh PHP .. Ingatlah ini adalah cara PERFORMING menghapus file. $ absolutePathToFolder HARUS diperiksa dan diamankan sebelum menjalankan kode ini dan izin harus diberikan.

Solusi lain: Kelas ini menghapus semua file, subdirektori dan file dalam sub direktori.

class Your_Class_Name {
    /**
     * @see http://php.net/manual/de/function.array-map.php
     * @see http://www.php.net/manual/en/function.rmdir.php 
     * @see http://www.php.net/manual/en/function.glob.php
     * @see http://php.net/manual/de/function.unlink.php
     * @param string $path
     */
    public function delete($path) {
        if (is_dir($path)) {
            array_map(function($value) {
                $this->delete($value);
                rmdir($value);
            },glob($path . '/*', GLOB_ONLYDIR));
            array_map('unlink', glob($path."/*"));
        }
    }
}

fungsi unlinkr secara rekursif menghapus semua folder dan file di jalur yang diberikan dengan memastikan tidak menghapus skrip itu sendiri.

function unlinkr($dir, $pattern = "*") {
    // find all files and folders matching pattern
    $files = glob($dir . "/$pattern"); 

    //interate thorugh the files and folders
    foreach($files as $file){ 
    //if it is a directory then re-call unlinkr function to delete files inside this directory     
        if (is_dir($file) and !in_array($file, array('..', '.')))  {
            echo "<p>opening directory $file </p>";
            unlinkr($file, $pattern);
            //remove the directory itself
            echo "<p> deleting directory $file </p>";
            rmdir($file);
        } else if(is_file($file) and ($file != __FILE__)) {
            // make sure you don't delete the current script
            echo "<p>deleting file $file </p>";
            unlink($file); 
        }
    }
}

jika Anda ingin menghapus semua file dan folder tempat Anda menempatkan skrip ini, panggil sebagai berikut

//get current working directory
$dir = getcwd();
unlinkr($dir);

jika Anda hanya ingin menghapus file php saja, panggil saja sebagai berikut

unlinkr($dir, "*.php");

anda dapat menggunakan jalur lain untuk menghapus file juga 

unlinkr("/home/user/temp");

Ini akan menghapus semua file di direktori home/user/temp.

Diposting file tujuan umum dan penanganan folder untuk menyalin, memindahkan, menghapus, menghitung ukuran, dll., Yang dapat menangani satu file atau satu set folder. 

https://Gist.github.com/4689551

Menggunakan: 

Untuk menyalin (atau memindahkan) satu file atau satu set folder/file:

$files = new Files();
$results = $files->copyOrMove('source/folder/optional-file', 'target/path', 'target-file-name-for-single-file.only', 'copy');

Hapus satu file atau semua file dan folder di jalur:

$files = new Files();
$results = $files->delete('source/folder/optional-file.name');

Hitung ukuran satu file atau satu set file dalam satu set folder:

$files = new Files();
$results = $files->calculateSize('source/folder/optional-file.name');

 <?
//delete all files from folder  & sub folders
function listFolderFiles($dir)
{
    $ffs = scandir($dir);
    echo '<ol>';
    foreach ($ffs as $ff) {
        if ($ff != '.' && $ff != '..') {
            if (file_exists("$dir/$ff")) {
                unlink("$dir/$ff");
            }
            echo '<li>' . $ff;
            if (is_dir($dir . '/' . $ff)) {
                listFolderFiles($dir . '/' . $ff);
            }
            echo '</li>';
        }
    }
    echo '</ol>';
}
$arr = array(
    "folder1",
    "folder2"
);
for ($x = 0; $x < count($arr); $x++) {
    $mm = $arr[$x];
    listFolderFiles($mm);
}
//end
?> 

Bagi saya, solusi dengan readdir adalah yang terbaik dan bekerja seperti pesona. Dengan glob, fungsi gagal dengan beberapa skenario.

// Remove a directory recursively
function removeDirectory($dirPath) {
    if (! is_dir($dirPath)) {
        return false;
    }

    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }

    if ($handle = opendir($dirPath)) {

        while (false !== ($sub = readdir($handle))) {
            if ($sub != "." && $sub != ".." && $sub != "Thumb.db") {
                $file = $dirPath . $sub;

                if (is_dir($file)) {
                    removeDirectory($file);
                } else {
                    unlink($file);
                }
            }
        }

        closedir($handle);
    }

    rmdir($dirPath);
}

Ada paket yang disebut "Pusheh". Dengan menggunakannya, Anda dapat menghapus direktori atau menghapus direktori sepenuhnya ( Github link ). Ini tersedia di Pembuat paket , juga.

Misalnya, jika Anda ingin menghapus direktori Temp, Anda dapat melakukan:

Pusheh::clearDir("Temp");

// Or you can remove the directory completely
Pusheh::removeDirRecursively("Temp");

Jika Anda tertarik, lihat wiki .

Saya memperbarui jawaban @Stichoza untuk menghapus file melalui subfolder.

function glob_recursive($pattern, $flags = 0) {
    $fileList = glob($pattern, $flags);
    foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
        $subPattern = $dir.'/'.basename($pattern);
        $subFileList = glob_recursive($subPattern, $flags);
        $fileList = array_merge($fileList, $subFileList);
    }
    return $fileList;
}

function glob_recursive_unlink($pattern, $flags = 0) {
    array_map('unlink', glob_recursive($pattern, $flags));
}

public static function recursiveDelete($dir)
{
    foreach (new \DirectoryIterator($dir) as $fileInfo) {
        if (!$fileInfo->isDot()) {
            if ($fileInfo->isDir()) {
                recursiveDelete($fileInfo->getPathname());
            } else {
                unlink($fileInfo->getPathname());
            }
        }
    }
    rmdir($dir);
}