PHP - Remove '.' and '..' from values fetched from directory files - php

I am using this code in order to get a list files from directory:
$dir = '/restosnapp_cms/images/';
if ($dp = opendir($_SERVER['DOCUMENT_ROOT'] . $dir)) {
$files = array();
while (($file = readdir($dp)) !== false) {
if (!is_dir($dir . $file)) {
$files[] = $file;
}
}
closedir($dp);
} else {
exit('Directory not opened.');
}
I want to get rid of the values '.' and '..'.
Is it possible to do this? Thank you. :)

Just check for them first:
while ($file = readdir($p)) {
if ($file == '.' || $file == '..') {
continue;
}
// rest of your code
}

DirectoryIterator is much more fun than *dir functions:
$dir = new DirectoryIterator($_SERVER['DOCUMENT_ROOT'] . $dir);
foreach($dir as $file) {
if (!$file->isDir() && !$file->isDot()) {
$files[] = $file->getPathname();
}
}
But the bottomline is regardless of which way you do it, you need to use a conditional.

Related

PHP Multi Directory delete

So I'm creating an image upload site and I need to delete multiple directories and files simultaneously. I have managed to create code that does the job however I'm unsure whether this is 'good code' as I'm repeating myself.
Is there a better way to write the below?
$dirname = 'uploads/'.$album_id;
$dirnamethumb = 'uploads/thumbs/'.$album_id;
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}
if (is_dir($dirnamethumb))
$dir_handle = opendir($dirnamethumb);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirnamethumb."/".$file))
unlink($dirnamethumb."/".$file);
else
delete_directory($dirnamethumb.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
rmdir($dirnamethumb);
return true;
Thank you in advance for your help!
Why not try this recursive function from similar question
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file))
rrmdir($file);
else
unlink($file);
} rmdir($dir);
}
try this,
$dir = '/path/to/some/dir/'; // notice: trailing slash!
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if (is_dir($dir . $entry) ) {
rmdir($dir . $entry);
}
}
closedir($handle);
}
?>

PHP: Remove folders and files in them but keep main directory

I have a directory /main with folders and files inside those folders.
I want to keep directory /main but delete everything in it:
$di = new RecursiveDirectoryIterator('/main');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
if(!is_dir($filename)){
unlink($filename);
}
};
This is deleting the files inside the folders, leaving /main with a list of empty folders, how do I delete these now?
I know this should be possible to integrate inside the loop, I tried rmdir without success.
Try this code
UPDATED ANSWER:
$dir = '/home/XXXXX/public_html/';
foreach(glob($dir.'*.*') as $v){
echo $v;
// unlink($v);
}
destroy_dir($dir);
function destroy_dir($dir) {
if (!is_dir($dir) || is_link($dir)) return unlink($dir);
foreach (scandir($dir) as $file) {
if ($file == '.' || $file == '..') continue;
if (!destroy_dir($dir . DIRECTORY_SEPARATOR . $file)) {
chmod($dir . DIRECTORY_SEPARATOR . $file, 0777);
if (!destroy_dir($dir . DIRECTORY_SEPARATOR . $file)) return false;
};
}
return rmdir($dir);
}
Here, Code is not tested.
function delete_directory_files($dirname) {
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}
closedir($dir_handle);
return true;
}

Readdir images from subdirectories and SORT alphabetically?

i found this code (https://stackoverflow.com/a/9628457/1510766) for show all images from directories and sub-directories, and works fine, but im trying to implement the sort() function of php but doesnt work:
function ListFiles($dir) {
if($dh = opendir($dir)) {
$files = Array();
$inner_files = Array();
while($file = readdir($dh)) {
if($file != "." && $file != ".." && $file[0] != '.') {
if(is_dir($dir . "/" . $file)) {
$inner_files = ListFiles($dir . "/" . $file);
if(is_array($inner_files)) $files = array_merge($files, $inner_files);
} else {
array_push($files, $dir . "/" . $file);
}
}
}
closedir($dh);
// -- SORTING the FILES --
sort($files);
return $files;
}
}
foreach (ListFiles('works/'.$service_get_var.'/') as $key=>$file){
echo "<li><img src=\"$file\"/></li>";
}
When I test this, I cant see any images, is the correct use for sort()?. Thank you very much.
Sort after read all, not in recursive steps
function ListFiles($dir) {
if($dh = opendir($dir)) {
$files = Array();
$inner_files = Array();
while($file = readdir($dh)) {
if($file != "." && $file != ".." && $file[0] != '.') {
if(is_dir($dir . "/" . $file)) {
$inner_files = ListFiles($dir . "/" . $file);
if(is_array($inner_files)) $files = array_merge($files, $inner_files);
} else {
array_push($files, $dir . "/" . $file);
}
}
}
closedir($dh);
// -- SORTING the FILES --
//sort($files);
return $files;
}
}
$list = ListFiles('works/'.$service_get_var.'/');
sort($list);
foreach ($list as $key=>$file){
echo "<li><img src=\"$file\"/></li>";
}

Delete a directory not empty

rmdir("./uploads/temp/".$user."/");
I have many files in a directory I wish to remove in my PHP script, however these is no way for me to unlink() the file first. Is there a way I co do
unlink(* FROM (dir=)) // don't downvote the long shot
// delete all files from the dir first
// then delete that dir
Reference a directory has to be empty in order to delete it, see php.net/manual/en/function.rmdir.php
You can use the DirectoryIterator and unlink together.
use this
function delete_directory($dirname) {
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
return true;
}
This code can easily be improved upon, as it's a quick hack, but it takes a directory as an argument and then uses functional recursion to delete all files and folders within, and then finally removes the directory. Nice and quick, too.
There is no other way except to delete all files first using one way or another and then remove directory.
public static function deleteDir($dirPath) {
if (! is_dir($dirPath)) {
throw new InvalidArgumentException('$dirPath must be a directory');
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
$dirPath .= '/';
}
$files = glob($dirPath . '*', GLOB_MARK);
foreach ($files as $file) {
if (is_dir($file)) {
self::deleteDir($file);
} else {
unlink($file);
}
}
rmdir($dirPath);
}
Try using glob to loop over the files in the directory to delete
foreach (glob('/path/to/directory/*') as $file){
unlink('/path/to/directory/' . $file);
}
Check this http://lixlpixel.org/recursive_function/php/recursive_directory_delete/
function recursive_remove_directory($directory, $empty=FALSE)
{
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
if(!file_exists($directory) || !is_dir($directory))
{
return FALSE;
}elseif(is_readable($directory))
{
$handle = opendir($directory);
while (FALSE !== ($item = readdir($handle)))
{
if($item != '.' && $item != '..')
{
$path = $directory.'/'.$item;
if(is_dir($path))
{
recursive_remove_directory($path);
}else{
unlink($path);
}
}
}
closedir($handle);
if($empty == FALSE)
{
if(!rmdir($directory))
{
return FALSE;
}
}
}
return TRUE;
}
You can delete it recursively:
public function delete_folder ($path) {
$handle = opendir($path);
while ($file = readdir($handle)) {
if ($file != '..' && $file != '.') {
if (is_file($path . DS . $file))
unlink($path . DS . $file);
else
delete_folder($path . DS . $file);
}
}
closedir($handle);
rmdir($tmp_path);
}
delete_folder('path/to/folder');

PHP list directories and remove .. and

I created a script that list the directories in the current directory
<?php
$dir = getcwd();
if($handle = opendir($dir)){
while($file = readdir($handle)){
if(is_dir($file)){
echo "$file<br />";
}
}
?>
but the problem is, I am seeing this ".." and "." right above the directory listings, when someone clicks it, they get redirected one level up the directories.. can someone tell me how to remove those ".." and "." ?
If you use opendir/readdir/closedir functions, you have to check manually:
<?php
if ($handle = opendir($dir)) {
while ($file = readdir($handle)) {
if ($file === '.' || $file === '..' || !is_dir($file)) continue;
echo "$file<br />";
}
}
?>
If you want to use DirectoryIterator, there is isDot() method:
<?php
$iterator = new DirectoryIterator($dir);
foreach ($iterator as $fileInfo) {
if ($fileInfo->isDot() || !$fileInfo->isDir()) continue;
$file = $fileinfo->getFilename();
echo "$file<br />";
}
?>
Note: I think that continue can simplify this kind of loops by reducing indentation level.
Or use glob:
foreach(glob('/path/*.*') as $file) {
printf('%s<br/>', $file, $file);
}
If your files don't follow the filename dot extension pattern, use
array_filter(glob('/path/*'), 'is_file')
to get an array of (non-hidden) filenames only.
Skips all hidden and "dot directories":
while($file = readdir($handle)){
if (substr($file, 0, 1) == '.') {
continue;
}
Skips dot directories:
while($file = readdir($handle)){
if ($file == '.' || $file == '..') {
continue;
}
<?php
if($handle = opendir($dir)){
while($file = readdir($handle)){
if(is_dir($file) && $file !== '.' && $file !== '..'){
echo "$file<br />";
}
}
}
?>

Categories