note 127472 added to function.unlink

From: Date: Tue, 09 Aug 2022 14:59:15 +0000
Subject: note 127472 added to function.unlink
Groups: php.notes 
Request: Send a blank email to php-notes+get-219411@lists.php.net to get a copy of this message
if you're looking for a recursive unlink: <?php /** * delete a file or directory * automatically traversing directories if needed. * PS: has not been tested with self-referencing symlink shenanigans, that might cause a infinite recursion, i don't know. * * @param string $cmd * @throws \RuntimeException if unlink fails * @throws \RuntimeException if rmdir fails * @return void */ function unlinkRecursive(string $path, bool $verbose = false): void { if (!is_readable($path)) { return; } if (is_file($path)) { if ($verbose) { echo "unlink: {$path}\n"; } if (!unlink($path)) { throw new \RuntimeException("Failed to unlink {$path}: " . var_export(error_get_last(), true)); } return; } $foldersToDelete = array(); $filesToDelete = array(); // we should scan the entire directory before traversing deeper, to not have open handles to each directory: // on very large director trees you can actually get OS-errors if you have too many open directory handles. foreach (new DirectoryIterator($path) as $fileInfo) { if ($fileInfo->isDot()) { continue; } if ($fileInfo->isDir()) { $foldersToDelete[] = $fileInfo->getRealPath(); } else { $filesToDelete[] = $fileInfo->getRealPath(); } } unset($fileInfo); // free file handle foreach ($foldersToDelete as $folder) { unlinkRecursive($folder, $verbose); } foreach ($filesToDelete as $file) { if ($verbose) { echo "unlink: {$file}\n"; } if (!unlink($file)) { throw new \RuntimeException("Failed to unlink {$file}: " . var_export(error_get_last(), true)); } } if ($verbose) { echo "rmdir: {$path}\n"; } if (!rmdir($path)) { throw new \RuntimeException("Failed to rmdir {$path}: " . var_export(error_get_last(), true)); } } ?> ---- Server IP: 45.112.84.4 Probable Submitter: 185.85.3.173 (proxied: 84.49.158.188) ---- Manual Page -- https://php.net/manual/en/function.unlink.php Edit -- https://main.php.net/note/edit/127472 Del: integrated -- https://main.php.net/note/delete/127472/integrated Del: useless -- https://main.php.net/note/delete/127472/useless Del: bad code -- https://main.php.net/note/delete/127472/bad+code Del: spam -- https://main.php.net/note/delete/127472/spam Del: non-english -- https://main.php.net/note/delete/127472/non-english Del: in docs -- https://main.php.net/note/delete/127472/in+docs Del: other reasons-- https://main.php.net/note/delete/127472 Reject -- https://main.php.net/note/reject/127472 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#219411) next »