Array of file names needs sorting [duplicate] - php

I'm using the following PHP code to list all files and folders under the current directory:
<?php
$dirname = ".";
$dir = opendir($dirname);
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != "..") and ($file != "index.php"))
{
echo("<a href='$file'>$file</a> <br />");
}
}
?>
The problem is list is not ordered alphabetically (perhaps it's sorted by creation date? I'm not sure).
How can I make sure it's sorted alphabetically?

The manual clearly says that:
readdir
Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.
What you can do is store the files in an array, sort it and then print it's contents as:
$files = array();
$dir = opendir('.'); // open the cwd..also do an err check.
while(false != ($file = readdir($dir))) {
if(($file != ".") and ($file != "..") and ($file != "index.php")) {
$files[] = $file; // put in array.
}
}
natsort($files); // sort.
// print.
foreach($files as $file) {
echo("<a href='$file'>$file</a> <br />\n");
}

<?php
function getFiles(){
$files=array();
if($dir=opendir('.')){
while($file=readdir($dir)){
if($file!='.' && $file!='..' && $file!=basename(__FILE__)){
$files[]=$file;
}
}
closedir($dir);
}
natsort($files); //sort
return $files;
}
?>
<html>
<head>
</head>
<body>
<h1> List of files </h1>
<ul class="dir">
<? foreach(getFiles() as $file)
echo "<li name='$file'><a href='$file'>$file</a></li>";
?>
</ul>
</body>
</html>

Using glob and sort it should work.

You could put all the directory names inside an array like:
$array[] = $file;
After that you can sort the array with:
sort($array);
And then print the links with that content.
I hope this help.

<?php
$dirname = ".";
$dir = opendir($dirname);
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != "..") and ($file != "index.php"))
{
$list[] = $file;
}
}
sort($list);
foreach($list as $item) {
echo("<a href='$item'>$item</a> <br />");
}
?>

I'd recommend moving away from the old opendir()/readdir(). Either use glob() or if you encounter a lot of files in a directory then use the DirectoryIterator Class(es):
http://www.php.net/manual/en/class.directoryiterator.php
http://www.php.net/manual/en/function.glob.php
Regards

You can use this beautiful script:
http://halgatewood.com/free-php-list-files-in-a-directory-script/

Related

How to hide file from list in directory

I have a script file. that list files and folder in a directory.. I want to hide certain files and folder. How do I do that?
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if (($file != ".")
&& ($file != ".."))
{
$thelist .= '<LI>'.$file.'';
}
}
closedir($handle);
}
?>
<P>List of files:</p>
<UL>
<P><?=$thelist?></p>
</UL>
<?php
$files_to_hide = array('file1.txt', 'file2.txt');
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if (($file != ".") && ($file != "..") && !in_array($file, $files_to_hide))
{
$thelist .= '<LI>'.$file.'';
}
}
closedir($handle);
}
?>
<P>List of files:</p>
<UL>
<P><?=$thelist?></p>
</UL>
Put the list of filenames you want to exclude in an array.
After that, you check whether the filename exists in the array before adding it to $thelist.
You can add that as part of the if() statement that checks if the filename is . or ...
Something like this:
<?php
$bannedFiles = Array(".", "..", "example");
if ($handle = opendir('.')){
while (false !== ($file = readdir($handle)))
{
$banned = false;
foreach ($bannedFiles as $bFile){
if ($bFile == $file){
$banned = true;
}
}
if (!$banned){
$thelist .= '<LI>'.$file.'</LI>';
}
}
closedir($handle);
}
?>
<P>List of files:</p>
<UL>
<P><? echo $thelist;?></p>
</UL>
If you know the names of the files/directories you want to hide, you can maintain a set-map of such entries, and filter them out within the while loop.
Your set-map would look like this:
$items_to_hide = [ "/home/me/top_secret" => 1, "/home/me/passwords.txt" => 1, ... ]
And then you would modfiy your while loop like this:
while (false !== ($file = readdir($handle)))
{
// check map if said file is supposed to be hidden, if so skip current loop iteration
if($items_to_hide[$file]) {
continue;
}
if (($file != ".")
&& ($file != ".."))
{
$thelist .= '<LI>'.$file.'';
}
}
Hope this helps.
EDIT:
Also wanted to mention, using a php ordered array as your "blacklist" is quite efficient, as a single lookup will occur in almost constant time. Hence you can grow your blacklist as large as you want and still see decent performance.

display random image url from folder

I have a php code which uses every image in a folder and echos the url on my page.
what i need help with is making the php code randomize the list of urls each time the page is loaded.
The code that i have is:
<?php
if ($handle = opendir('images')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$thelist .= '<div data-delay="5"><img src="images/'.$file.'"></div>';
}
}
closedir($handle);
}
?>
<?=$thelist?>
many thanks
Easiest solution would be to put all filenames into an array and then use shuffle() to mix it up. Then you can iterate over the array and output the images. It should look something like this:
<?php
$thelist = "";
if ($handle = opendir('images')) {
$images = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
array_push($images, 'images/'.$file);
}
}
closedir($handle);
shuffle($images);
foreach ($images as $image) {
$thelist .= '<div data-delay="5"><img src="'.$image.'"></div>';
}
echo $thelist;
}
?>
By using glob() instead of opendir() you could shorten the code significantly, as glob() returns an array and then you only would need to shuffle that one.
put your file links into an array and shuffle it with the function shuffle()
<?php
if ($handle = opendir('images')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach($fileTab as $file) {
$thelist .= '<div data-delay="5"><img src="images/'.$file.'"></div>';
}
}
?>
<?=$thelist?>
Instead of directly creating divs in the while loop, use it only to store all urls in an Array. Then shuffel that array, and use a foreach loop in order to populate $thelist.
Why don't you use glob()?
$images = glob('images/*.{jpg,png,gif}', GLOB_BRACE);
shuffle($images);
foreach($images as $image) {
echo '<div data-delay="5">
<img src="', $image ,'">
</div>';
}

Rename all files in a directory with numbers

I was wondering if anyone could help me write a PHP script for me that renames all the files in a directory in a sequence.
So...
DSC_10342.JPG -> 1.JPG
DSC_10343.JPG -> 2.JPG
DSC_10344.JPG -> 3.JPG
and so on.
Here's my version:
// open the current directory (change this to modify where you're looking)
$dir = opendir('.');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
// if the extension is '.jpg'
if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'jpg')
{
// do the rename based on the current iteration
$newName = $i . '.jpg';
rename($file, $newName);
// increase for the next loop
$i++;
}
}
// close the directory handle
closedir($dir);
Use rename to rename the files. You can use this handy script to loop through all files in a directory:
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
Then it's just a matter of looking at the filenames ($file) and figuring out what number to give them. If you need more help than that, just tell me and I'll give more details.
Try this:
$handler = opendir($directory);
$index = 1;
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
rename($directory."/".$file, $directory."/".$index.".JPG");
$index++;
}
}
closedir($handler);
Using someone's snippet it would look like this:
<?php
$path = '.';
$i = 1;
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && is_file($path.'/'.$file)) {
$oldname = $path.'/'.$file;
$path_info = pathinfo($oldname);
rename($oldname, $path.'/'.($i++).'.'.$path_info['extension']);
}
}
closedir($handle);
}
?>
It will rename files with all extensions and skip directories that may be inside your directory.

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 />";
}
}
}
?>

Evaluating PHP Code

I am very much a beginner when it comes to using PHP. I was given this code, to try and output the contents of a files on a folder, onto a server, but my issue is I do not know how to read and alter this code to fit my specific file path. Can someone help me out with this, and lets just use the name folder as an arbitrary pathname.
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
<?php
$dir_path = '.'; // '.' = current directory.
// '..' = parent directory.
// '/foo' = directory foo in the root file system
// 'folder' = a dir called 'folder' inside the current dir
// 'a/b' = folder 'b' inside 'a' inside the current dir
// '../a' = folder 'a' inside the parent directory
if ($handle = opendir($dir_path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
<?php
$path = '.';
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
Detailed explanation and examples: http://www.php.net/function.opendir

Categories