Read file names from directory - php

I am trying to read and display all the files in a directory using this code.
It works fine for files in the same directory as the script. But when I try to display files in a folder (files/) it is giving me problems.
I've tried setting the directoy variable to many different things. like...
files/
files
/files/
etc... nothing seems to work. Does anyone have any idea why?
<?php
$dhandleFiles = opendir('files/');
$files = array();
if ($dhandleFiles) {
while (false !== ($fname = readdir($dhandleFiles))) {
if (is_file($fname) && ($fname != 'list.php') && ($fname != 'error.php') && ($fname != 'index.php')) {
$files[] = (is_dir("./$fname")) ? "{$fname}" : $fname;
}
}
closedir($dhandleFiles);
}
echo "Files";
echo "<ul>";
foreach ($files as $fname) {
echo "<li><a href='{$fname}'>{$fname}</a></li>";
}
echo "</ul>";
?>

You're not including the full path in your array:
while($fname = readdir($dhandleFiles)) {
$files[] = 'files/' . $fname;
^^^^^^^^---must include actual path
}
Remember that readdir() returns ONLY the filename, without path information.

This should help - take a look at SplFileInfo too.
<?php
class ExcludedFilesFilter extends FilterIterator {
protected
$excluded = array(
'list.php',
'error.php',
'index.php',
);
public function accept() {
$isFile = $this->current()->isFile();
$isExcluded = in_array($this->current(), $this->excluded);
return $isFile && ! $isExcluded;
}
}
$dir = new DirectoryIterator(realpath('.'));
foreach (new ExcludedFilesFilter($dir) as $file) {
printf("%s\n", $file->getRealpath());
}

How about using glob function.
<?php
define('MYBASEPATH' , 'files/');
foreach (glob(MYBASEPATH . '*.php') as $fname) {
if($fname != 'list.php' && $fname != 'error.php' && $fname != 'index.php') {
$files[] = $fname;
}
}
?>
read more about getting all files in directory here

This reads and prints filenames from a sub-directory:
$d = dir("myfiles");
while (false !== ($entry = $d->read())) {
if ($entry != ".") {
if ($entry != "..") {
print"$entry";
}
}
}
$d->close();

Related

read files from an array in php

I'm trying to open a directory, read just files with a .txt format and then display the contents. I've coded it out, but it doesn't do anything, although it doesn't register any errors either. Any help?
$dir = 'information';
If (is_dir($dir)) {
$handle = opendir($dir);
} else {
echo "<p>There is a system error</p>";
}
$entry=array();
while(false!==($file = readdir($handle))) {
if ( !strcmp($file, ".") || !strcmp($file, "..")) {
}
else if(substr($file, -4) == '.txt') {
$entry[] = $file;
}
foreach ($entry as $txt_file) {
if(is_file($txt_file) && is_writable($txt_file)) {
$file_open = fopen($txt_file, 'r');
while (!feof($file_open)) {
echo"<p>$file_open</p>";
}
}
}
}
Help is quite simple.
Instead
$dir = 'information';
If (is_dir($dir)) {
$handle = opendir($dir);
} else {
echo "<p>There is a system error</p>";
}
write (I am sorry for re-formatting of new lines)
$dir = 'information';
if(is_dir($dir))
{
$handle = opendir($dir);
}
else
{
echo "<p>There is a system error</p>";
}
because if has to be written only smallcaps, thus not If.
And the second part rewrite to (again, you may use your own formatting of new lines)
$entry=array();
$file = readdir($handle);
while($file !== false)
{
if(!strcmp($file, ".") || !strcmp($file, ".."))
{
}
elseif(substr($file, -4) == '.txt')
{
$entry[] = $file;
}
foreach ($entry as $txt_file)
{
if(is_file($txt_file) && is_writable($txt_file))
{
$file_open = fopen($txt_file, 'r');
while(!feof($file_open))
{
echo"<p>$file_open</p>";
}
}
}
}
because PHP has elseif, not else if like JavaScript. Also I separated $file = readdir($handle) for possible source of error.
Code part
if(!strcmp($file, ".") || !strcmp($file, ".."))
{
}
elseif(substr($file, -4) == '.txt')
{
$entry[] = $file;
}
should be shortened only to
if(substr($file, -4) == '.txt')
{
$entry[] = $file;
}
because when if part is empty, then it is not neccessary.
That is all I can do for you at this time.
Instead of iterating the directory with readdir, consider using glob() instead. It allows you to specify a pattern and it returns all files that match it.
Secondly, your while loop has an error: you conditionally add the file name to the list of files, but then you always print every file name using a foreach loop. On the first loop it will print the first file. On the second loop it will print the first and second files, etc. You should separate your while and foreach loops to fix that issue (i.e. unnest them).
Using glob, the modified code will look like:
$file_list = glob('/path/to/files/*.txt');
foreach ($file_list as $file_name) {
if (is_file($file_name) && is_writable($file_name)) {
// Do something with $file_name
}
}

PHP Directory, subdirectory and file Listing default sort order

i want to list all directory, sub-directory and files using php.
i have tried following code. it returns all the directory, sub directory and files but it's not showing in correct order.
for ex:default order is 1dir, 2dir, 7dir, 8dir while in browser it shows 1dir, 8dir, 7dir, 2dir which is not correct.
code:
function createDir($path = '.')
{
if ($handle = opendir($path))
{
echo "<ul>";
while (false !== ($file = readdir($handle)))
{
if (is_dir($path.$file) && $file != '.' && $file !='..') {
printSubDir($file, $path);
}
else if ($file != '.' && $file !='..'){
$allowed = array('pdf','doc','docx','xls','xlsx','jpg','png','gif','mp4','avi','3gp','flv','mov','PDF','DOC','DOCX','XLS','XLSX','JPG','PNG','GIF','MP4','AVI','3GP','FLV','MOV','html','HTML','css','CSS','js','JS');
$ext = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($ext,$allowed) ) {
$queue[] = $file;
}
}
}
printQueue($queue, $path);
echo "</ul>";
}
}
function printQueue($queue, $path)
{
sort($queue);
foreach ($queue as $file)
{
//printFile($file, $path);
}
}
function printFile($file, $path) {
echo "<li><a href=\"".$path.$file."\" target='_blank'>$file</a></li>";
}
function printSubDir($dir, $path)
{
echo "<li><span class=\"toggle\">$dir</span>";
createDir($path.$dir."/");
echo "</li>";
}
createDir($path);
?>
need help to fix the code and display the direcotry , subdirectory and files in correct order.
I'm having the same problem during listing a directory files. But I have used DirectoryLister
This code is very useful. You can list out your files easily.
You can implement it by following steps.
Download and extract Directory Lister
Copy resources/default.config.php to resources/config.php
Upload index.php and the resources folder to the folder you want listed
Upload additional files to the same directory as index.php
I hope this might help you
You can start by looping the array and printing each directory:
public function dirtree($dir, $regex='', $ignoreEmpty=false) {
if (!$dir instanceof DirectoryIterator) {
$dir = new DirectoryIterator((string)$dir);
}
$dirs = array();
$files = array();
foreach ($dir as $node) {
if ($node->isDir() && !$node->isDot()) {
// print_r($node);
$tree = dirtree($node->getPathname(), $ignoreEmpty);
// print"<pre>";print_r($tree);
if (!$ignoreEmpty || count($tree)) {
$dirs[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
$name = $node->getFilename();
//if ('' == $regex || preg_match($regex, $name)) {
$files[] = $name;
}
}
asort($dirs);
sort($files);
return array_merge($files, $dirs);
}
Use like this:
$fileslist = dirtree('root');
echo "<pre style='font-size:15px'>";
print_r($fileslist);

list directory in PHP hide extension

I have been searching for a way to hide an extension which appears from the directory list. I am showing these directory in a website menu but I would like all files to appear with their extension next to the file name. For example file.pdf and file.png.
I need to hide the extension from these files to appear as ( file , file , img , etc..).
php code:
<?php
$path = "./outgoing/";
function createDir($path = '.')
{
if ($handle = opendir($path))
{
echo "<ul>";
while (false !== ($file = readdir($handle)))
{
if (is_dir($path.$file) && $file != '.' && $file !='..')
printSubDir($file, $path, $queue);
else if ($file != '.' && $file !='..')
$queue[] = $file;
}
printQueue($queue, $path);
echo "</ul>";
}
}
function printQueue($queue, $path)
{
foreach ($queue as $file)
{
printFile($file, $path);
}
}
function printFile($file, $path)
{
echo "<li>$file</li>";
}
function printSubDir($dir, $path)
{
echo "<li><span class=\"toggle\">$dir</span>";
createDir($path.$dir."/",".pdf");
echo "</li>";
}
createDir($path);
?>
Use something like this to remove ext
$temp = explode(".", $file);
$par = $temp[0];

Checking for string within a directory of files but not including subdirectories

I'm trying to write a program that will open up a directory (in this case: files/), scan all of the filenames (not including any directories or ".." or ".") within this directory, and search for the filenames in the specified files from the "pages" array. If the filename is NOT found in the pages, the file will be moved to "unused-content".
My current code does not work. How can I achieve this goal?
<?php
if($handle = opendir('files/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$file_names[] = $entry;
}
}
closedir($handle);
}
$pages = array("page1.html","page2.shtml","page_three.shtml","page4.htm","page5.shtml");
for($x=0; $x<sizeOf($pages); $x++) {
$current_page = file_get_contents($pages[$x]);
for($i=0; $i<sizeOf($file_names); $i++) {
if(!strpos($current_page,$file_names[$i])) {
if (copy("files/".$file_names[$i],"files/unused-content/".$file_names[$i])) {
unlink("files/".$file_names[$i]);
}
}
}
}
?>
Thank you!
You don't need all that long code .. all you need is FilesystemIterator
$pages = array("1.xml","page2.shtml","page_three.shtml","page4.htm","page5.shtml");
$dir = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
foreach ( $dir as $file ) {
if ($file->isFile() && in_array(strlen($file->getFilename()), $pages)) {
// copy
// unlink
}
}
See another example using GlobIterator
Try to do something like this:
<?php
if($handle = opendir('files/')) {
$i=0;
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$file_names[$i] = $entry;
}
$i++;
}
closedir($handle);
}
$pages = array("page1.html","page2.shtml","page_three.shtml","page4.htm","page5.shtml");
for($x=0; $x<sizeOf($pages); $x++) {
$current_page = file_get_contents($pages[$x]);
for($i=0; $i<sizeOf($file_names); $i++) {
if(!strpos($current_page,$file_names[$i])) {
if (copy("files/".$file_names[$i],"files/unused-content/".$file_names[$i])) {
unlink("files/".$file_names[$i]);
}
}
}
}
?>

delete multiple files from the folder

how can i delete multiple files from the folder?
code:$query=$this->main_model->get($id);
if($query->num_rows()>0)
{
foreach ($query->result() as $row)
{
unlink("uploads/".$id."/".$row->img_name);
unlink("uploads/".$id."/".$row->img_name_tn);
unlink("uploads/".$id."/".$row->file);
unlink("uploads/".$id."/".$row->file2);
unlink("uploads/".$id."/Thumbs.db");
}
rmdir("uploads/".$id);
}
here is the code i used but it delete the files at ones. and how can i delete all files from the folder?
originally from php.net:
<?php
$dir = '/uploads/';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") { // strip the current and previous directory items
unlink($dir . $file); // you can add some filters here, aswell, to filter datatypes, file, prefixes, suffixes, etc
}
}
closedir($handle);
}
?>
I found this at php.net:
"The shortest recursive delete possible"
function rrmdir($path) {
return is_file($path)?
#unlink($path):
array_map('rrmdir',glob($path.'/*'))==#rmdir($path)
;
}
You could do it like this:
function delete_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);
}
}
closedir($dir_handle);
return true;
}
You need to use a recursive function. A comment from the rmdir page have written a function on how to do it, see http://www.php.net/manual/en/function.rmdir.php#98622. This code will delete the folder and everything in it.
<?php
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
?>

Categories