PHPスクリプトを使用して、ディレクトリからすべてのテキストファイルを削除しようとしています。
これが私が試したことです.....
<?php array_map('unlink', glob("/paste/*.txt")); ?>
これを実行してもエラーは発生しませんが、機能しません。
このためのスニペットはありますか? 他に何を試すべきかわかりません。
あなたの実装はあなたがする必要があるすべてが使用することで動作しますUse full PATH
例
$fullPath = __DIR__ . "/test/" ;
array_map('unlink', glob( "$fullPath*.log"))
よくあることですが、下にあるテキスト ファイルのリンクを柔軟かつ再帰的に解除できるように、提出された回答を少し拡張しました。
// @param string Target directory
// @param string Target file extension
// @return boolean True on success, False on failure
function unlink_recursive($dir_name, $ext) {
// Exit if there's no such directory
if (!file_exists($dir_name)) {
return false;
}
// Open the target directory
$dir_handle = dir($dir_name);
// Take entries in the directory one at a time
while (false !== ($entry = $dir_handle->read())) {
if ($entry == '.' || $entry == '..') {
continue;
}
$abs_name = "$dir_name/$entry";
if (is_file($abs_name) && preg_match("/^.+\.$ext$/", $entry)) {
if (unlink($abs_name)) {
continue;
}
return false;
}
// Recurse on the children if the current entry happens to be a "directory"
if (is_dir($abs_name) || is_link($abs_name)) {
unlink_recursive($abs_name, $ext);
}
}
$dir_handle->close();
return true;
}
以下の方法を変更できますが、注意してください。ファイルを削除する権限があることを確認してください。他のすべてが失敗した場合は、exec コマンドを送信し、Linux に実行させます。
static function getFiles($directory) {
$looper = new RecursiveDirectoryIterator($directory);
foreach (new RecursiveIteratorIterator($looper) as $filename => $cur) {
$ext = trim($cur->getExtension());
if($ext=="txt"){
// remove file:
}
}
return $out;
}
削除方法を知りたい場合 (たとえば、パブリック ディレクトリにあるすべての PDF ファイル) は、次のように実行できます。
array_map('unlink', glob( public_path('*.pdf')));