Control the order of the files with opendir() & readdir() - php

I checked at php.net opendir() but found no way to control the order of the files that opendir() gets.
I have a slideshow and I have problems controling the order of the images. I tried changing names and use 01.img,02.img,...,20.img but no sucess.
My script:
<?php
$path2 = "./img/";
function createDir($path2 = './img'){
if ($handle = opendir($path2)){
echo "<ul class=\"ad-thumb-list\">";
while (false !== ($file = readdir($handle))){
if (is_dir($path2.$file) && $file != '.' && $file !='..')
printSubDir($file, $path2, $queue);
else if ($file != '.' && $file !='..')
$queue[] = $file;
}
printQueue($queue, $path2);
echo "</ul>";
}
}
function printQueue($queue, $path2){
foreach ($queue as $file){
printFile($file, $path2);
}
}
function printFile($file, $path2){
if ($file=="thumbs.db") {echo "";}
else{
echo "<li><a href=\"".$path2.$file."\">";
echo "<img src=\"".$path2.$file."\" class='thumbnail'></a></li>";
}
}
/*function printSubDir($dir, $path2)
{
}*/
createDir($path2);
?>

Use scandir() and natsort().
Rewritten code:
function createDir($path2 = './img'){
$dirContents = scandir($path2);
natsort($dirContents);
echo "<ul class=\"ad-thumb-list\">";
// You should actually add the line below!
// $queue = array();
foreach ($dirContents as $entry) {
if ($entry == '.' || $entry == '..') {
continue;
}
$entryPath = $path2 . $entry;
if (is_dir($entryPath)) {
printSubDir($entry, $path2, $queue);
}
else {
$queue[] = $entry;
}
}
printQueue($queue, $path2);
echo "</ul>";
}
}

If you are using PHP 5, you could try using scandir() instead. It has an argument for sorting.
http://us1.php.net/scandir
array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )

As #Steven has already said, you may not be able to change the output of opendir(), but there's nothing stopping you from sorting the array afterwards.
To do this, have a look at the natsort() function, which is designed to properly sort strings like those you're using for file names.

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);

Php list files in a directory and remove extention

I use this php code to retrieve the files stored in a directory .
if ($handle = opendir('FolderPath')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n <br />" ;
}
}
closedir($handle);
}
This Directory only holds PHP files , how would i be able to remove the extension from the echoed results? example: ( index.php would become index )
The easiest way to do this is by using the glob function:
foreach (glob('path/to/files/*.php') as $fileName) {
//extension .php is guaranteed here
echo substr($fileName, 0, -4), PHP_EOL;
}
The advantages of glob here is that you can do away with those pesky readdir and opendir calls. The only slight "disatvantage" is that the value of $fileName will contain the path, too. However, that's an easy fix (just add one line):
foreach (glob('path/to/files/*.php') as $fullName) {
$fileName = explode('/', $fullName);
echo substr(
end($fileName),//the last value in the array is the file name
0, -4),
PHP_EOL;
}
This should work for you:
echo basename($entry, ".php") . "\n <br />" ;
A quick way to do this is
<?php
if ($handle = opendir('FolderPath')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);
echo $file_name;
}
}
closedir($handle);
?>
$files = glob('path/to/files/*.*');
foreach($files as $file) {
if (! is_dir($file)) {
$file = pathinfo($file);
echo "<br/>".$file['filename'];
}
}
Use pathinfo()
$entry = substr($entry, 0, strlen($entry) - 4);
Note that this is a simple and quick solution which works perfect if you are 100% sure that your extension is in the form of *.xxx. However if you need a more flexible and safer solution regarding possible different extension lenghts, than this solution is not recommended.
Elegant solution would be to use $suffix attribute of DirectoryIterator::getBasename() method. When provided, $suffix will be removed on each call. For known extension, you can use:
foreach (new DirectoryIterator('/full/dir/path') as $file) {
if ($file->isFile()) {
print $file->getBasename('.php') . "\n";
}
}
or this, as an universal solution:
foreach (new DirectoryIterator('/full/dir/path') as $file) {
if ($file->isFile()) {
print $file->getBasename($file->getExtension() ? '.' . $file->getExtension() : null) . "\n";
}
}
PHP docs: http://php.net/manual/en/directoryiterator.getbasename.php

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];

PHP - Code to traverse a directory and get all the files(images)

i want to write a page that will traverse a specified directory.... and get all the files in that directory...
in my case the directory will only contain images and display the images with their links...
something like this
How to Do it
p.s. the directory will not be user input.. it will be same directory always...
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
use readdir
<?php
//define directory
$dir = "images/";
//open directory
if ($opendir = opendir($dir)){
//read directory
while(($file = readdir($opendir))!= FALSE ){
if($file!="." && $file!= ".."){
echo "<img src='$dir/$file' width='80' height='90'><br />";
}
}
}
?>
source: phpacademy.org
You'll want to use the scandir function to walk the list of files in the directory.
Hi you can use DirectoryIterator
try {
$dir = './';
/* #var $Item DirectoryIterator */
foreach (new DirectoryIterator($dir) as $Item) {
if($Item->isFile()) {
echo $Item->getFilename() . "\n";
}
}
} catch (Exception $e) {
echo 'No files Found!<br />';
}
If you want to pass directories recursively:
http://php.net/manual/en/class.recursivedirectoryiterator.php
/**
* function get files
* #param $path string = path to fine files in
* #param $accept array = array of extensions to accept
* #param currentLevel = 0, stopLevel = 0
* #return array of madmanFile objects, but you can modify it to
* return whatever suits your needs.
*/
public static function getFiles( $path = '.', $accept, $currentLevel = 0, $stopLevel = 0){
$path = trim($path); //trim whitespcae if any
if(substr($path,-1)=='/'){$path = substr($path,0,-1);} //cutoff the last "/" on path if provided
$selectedFiles = array();
try{
//ignore these files/folders
$ignoreRegexp = "/\.(T|t)rash/";
$ignore = array( 'cgi-bin', '.', '..', '.svn');
$dh = #opendir( $path );
//Loop through the directory
while( false !== ( $file = readdir( $dh ) ) ){
// Check that this file is not to be ignored
if( !in_array( $file, $ignore ) and !preg_match($ignoreRegexp,$file)){
$spaces = str_repeat( ' ', ( $currentLevel * 4 ) );
// Its a directory, so we need to keep reading down...
if( is_dir( "$path/$file" ) ){
//merge current selectFiles array with recursion return which is
//another array of selectedFiles
$selectedFiles = array_merge($selectedFiles,MadmanFileManager::getFiles( "$path/$file", $accept, ($currentLe$
} else{
$info = pathinfo($file);
if(in_array($info['extension'], $accept)){
$selectedFiles[] = new MadmanFile($info['filename'], $info['extension'], MadmanFileManager::getSize($
}//end if in array
}//end if/else is_dir
}
}//end while
closedir( $dh );
// Close the directory handle
}catch (Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
return $selectedFiles;
}
You could as others have suggested check every file in the dir, or you could use glob to identify files based on extension.
I use something along the lines of:
if ($dir = dir('images'))
{
while(false !== ($file = $dir->read()))
{
if (!is_dir($file) && $file !== '.' && $file !== '..' && (substr($file, -3) === 'jpg' || substr($file, -3) === 'png' || substr($file, -3) === 'gif'))
{
// do stuff with the images
}
}
}
else { echo "Could not open directory"; }
You could also try the glob function:
$path = '/your/path/';
$pattern = '*.{gif,jpg,jpeg,png}';
$images = glob($path . $pattern, GLOB_BRACE);
print_r($images);
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
For further reference :http://php.net/manual/en/function.opendir.php
I would start off by creating a recursive function:
function recurseDir ($dir) {
// open the provided directory
if ($handle = opendir($_SERVER['DOCUMENT_ROOT'].$dir)) {
// we dont want the directory we are in or the parent directory
if ($entry !== "." && $entry !== "..") {
// recursively call the function, if we find a directory
if (is_dir($_SERVER['DOCUMENT_ROOT'].$dir.$entry)) {
recurseDir($dir.$entry);
}
else {
// else we dont find a directory, in which case we have a file
// now we can output anything we want here for each file
// in your case we want to output all the images with the path under it
echo "<img src='".$dir.$entry."'>";
echo "<div><a href='".$dir.$entry."'>".$dir.$entry."</a></div>";
}
}
}
}
The $dir param needs to be in the following format:
"/path/" or "/path/to/files/"
Basically, just don't include the server root, because i have already done that below using $_SERVER['DOCUMENT_ROOT'].
So, in the end just call the recurseDir function we just made in your code once, and it will traverse any sub folders and output the image with the link under it.

Categories