read file name from directory - php

I want to read html file name from directory without any database. I have a code and its working properly, but two blank name it is giving, while I have only 4 file in directory.
<?php
if (is_dir('dir')) {
if ($dh = opendir('dir')) {
while (($file = readdir($dh)) !== false) {
echo "filename:".$file."<br />";
}
}
}?>
I have 4 html file and output should be:
filename:aaaaaa kjnnk_13.html
filename:aaaaaa kjnnk_2.html
filename:aaaaaa kjnnk_6.html
filename:aaaaaa kjnnk_9.html
But I found 2 extra filename:
filename:.
filename:..
filename:aaaaaa kjnnk_13.html
filename:aaaaaa kjnnk_2.html
filename:aaaaaa kjnnk_6.html
filename:aaaaaa kjnnk_9.html
Please help

. is for current dir
.. is for one directory up
When using readdir you will get those 2 extra.
I prefer using glob(). That function lets you filter for html files only too
<?php
$files = glob('dir/*html');
foreach($files as $file) {
echo "filename:".$file."<br />";
}
?>

Alternatively you could use FilesystemIterator which would skip the dot files by default:
$it = new FilesystemIterator('dir');
foreach ($it as $fileinfo) {
echo $fileinfo->getFilename() . "<br/>";
}
more answers in stackoverflow:
What exactly are the benefits of using a PHP 5 DirectoryIterator over PHP 4 "opendir/readdir/closedir"?
PHP: scandir() is too slow
Difference between DirectoryIterator and FileSystemIterator

Related

PHP - Reading the Contents of a Directory

So. I'm trying to make a simple PHP program that will read the contents of a directory. I've been working off W3Schools. And it's been working well, except for one small problem.
When this script runs, it posts two additional filen that don't exist - even if the directory is completely empty .
<?php
$dir = "./userphotos/";
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
print <<< HERE
<p>Filename: $file</p>
HERE;
}
closedir($dh);
}
}
?>
Any thoughts?
On Unix machines, each directory contains 2 hidden files.
. and .. these are references to the current and parent directories.
You should look into DirectoryInterator class
$dir = "./userphotos/";
foreach (new DirectoryIterator($dir) as $fileInfo) {
if($fileInfo->isDot() === false) {
echo $fileInfo->getFilename() . "<br>\n";
}
}
This example ignores the "dot" files
Also, you can look into RecursiveDirectoryIterator to do this recursively.

PHP Create Image Gallery From Directory And Subdirectories

I'm trying to make an image gallery that scans a main directory and creates a separate album for each subdirectory.
My structure is similar to this:
-Gallery
--Subdir 1
---Image 1
---Image 2
--Subdir 2
---Image 1
---Image 2
The idea is that each album is going to be made of a div with a class of web-gallery. Then there will be a header for the album title made from the subdirectories name. After that a list is generated of each image. This is going to be a one page gallery. If possible I would like to have a variable that sets how many albums are listed that way if I have 30 subdirectories my page doesn't get too crowded.
So far I've written this but it doesn't work. I'm not getting any errors or logs though it just doesn't work.
$dirs = glob('img/gallery_temp/*', GLOB_ONLYDIR);
foreach($dirs as $val) {
echo '<div class="web-gallery">';
echo "<h3><span>ยป</span> ".basename($val). "</h3>";
echo '<ul class="web-gallery-list">';
$files = glob($val.'*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
echo "<li><a href='".$file."'><img src='" . $file . "' alt='description'></a></li> \r\n";
}
echo "</ul>";
echo "</div>";
}
Simply add a / before *.{jpg,png,gif} like this:
$files = glob($val.'/*.{jpg,png,gif}', GLOB_BRACE);
This is because $val doesn't have a final / for the directory.
You might consider using "readdir" instead of glob. Glob is to find pathnames matching a pattern, see here: http://php.net/manual/en/function.glob.php and is known to be a bit problematic.
Readdir, if your directory is entirely images might be easier to use: http://php.net/manual/en/function.readdir.php
Couple this with is_dir() http://php.net/manual/en/function.is-dir.php to resolve your directories vs files. Here is a snippet
<?php
if ($handle = opendir('/galleries')) {
while (false !== ($entry = readdir($handle))) {
// this is a subdirectory
if (is_dir($entry)) {
}
// this is a file
else {
echo $entry;
}
}
closedir($handle);
}
?>
If you make it a recursive function you could actually have it traverse a number of subdirectories creating galleries within galleries.
I also found this fantastic little snippet that is very elegant on another stack question: Get Images In Directory and Subdirectory With Glob
$rdi = new RecursiveDirectoryIterator("uploads/prevImgs/");
$it = new RecursiveIteratorIterator($rdi);
foreach($it as $oneThing)
if (is_file($oneThing))
echo '<img src="'.$oneThing.'" /><br />';
Using SPL Library (PHP >= 5)
Better solution in your case
is to use SPL library (the most cross-platform)
$directory = new RecursiveDirectoryIterator("./img/gallery_temp", FilesystemIterator::SKIP_DOTS);
// Flatten the recursive iterator, folders come before their files
$it = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
foreach($it as $fileinfo)
{
if($fileinfo->isDir())
{
// prevPath used to separate each directory listing and closing the bracket UL list
$prevPath = $it->getSubPath().DIRECTORY_SEPARATOR.$fileinfo->getFilename();
echo sprintf
(
"<div class='web-gallery'>
<h3><span>></span> %s</h3>
<ul>".PHP_EOL,
$fileinfo->getFilename()
);
}
if($fileinfo->isFile())
{
echo sprintf("<li><a href=''><img src='%s/%s' alt='description'></a></li>".PHP_EOL, $it->getSubPath(), $fileinfo->getFilename());
if($prevPath != $it->getSubPath())
echo("</ul>");
}
}
Note:
For more informations : SPL Documentation
DIRECTORY_SEPARATOR is a cross-platform constant, will use the
correct directory separator of the OS where are executed the code
FilesystemIterator::SKIP_DOTS, avoid to fetch the '.' and '..' dir
link level.
you can limit the depth of scanning with $it->setMaxDepth(5);

php - list folders and files on localhost [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
List all folders on my computer (php)
I have tried:
$handle = opendir($path);
But what is the path? I put everything but the kitchen sink in there! I can't get it to work. I'm on my localhost right now.
I did:
opendir(dirname(__FILE__));
Here is what a got to work...
$dir = dirname(__FILE__);
// 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."<br />";
}
closedir($dh);
}
}
Will do some cleaning to get the information I was wanting. However, thanks to "some" of you on Stackoverflow I like this code alot better for localhost application.
foreach(glob("*") as $filename)
{
echo $filename."<br />";
}
$path is the path to the directory you want to open.
Like c:\users\MP123\Photos
or /home/MP123/Photos
This is really a "read the PHP manual, which has full examples for how to list folders and files", not an "ask professionals for help with my problem" type topic.
You're looking for glob (for easy stuff) or DirectoryIterator (for a more OOP approach).
(Examples from the respective doc pages w/ some modifications)
<?php
// all files in current directory (including '.' and '..')
foreach (glob("*") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
<?php
// all files in current directory (excluding'.' and '..')
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
}
}
?>

PHP: Using scandir(), folders are treated as files

Using PHP 5.3.3 (stable) on Linux CentOS 5.5.
Here's my folder structure:
www/myFolder/
www/myFolder/testFolder/
www/myFolder/testFile.txt
Using scandir() against the "myFolder" folder I get the following results:
.
..
testFolder
testFile.txt
I'm trying to filter out the folders from the results and only return files:
$scan = scandir('myFolder');
foreach($scan as $file)
{
if (!is_dir($file))
{
echo $file.'\n';
}
}
The expected results are:
testFile.txt
However I'm actually seeing:
testFile.txt
testFolder
Can anyone tell me what's going wrong here please?
You need to change directory or append it to your test. is_dir returns false when the file doesn't exist.
$scan = scandir('myFolder');
foreach($scan as $file)
{
if (!is_dir("myFolder/$file"))
{
echo $file.'\n';
}
}
That should do the right thing
Doesn't is_dir() take a file as a parameter?
$scan = scandir('myFolder');
foreach($scan as $file)
{
if (!is_dir($file))
{
echo $file.'\n';
}
}
Already told you the answer here: http://bugs.php.net/bug.php?id=52471
If you were displaying errors, you'd see why this isn't working:
Warning: Wrong parameter count for is_dir() in testFile.php on line 16
Now try passing $file to is_dir()
$scan = scandir('myFolder');
foreach($scan as $file)
{
if (!is_dir($file))
{
echo $file.'\n';
}
}
If anyone who comes here is interested in saving the output to an array, here's a fast way of doing that (modified to be more efficient):
$dirPath = 'dashboard';
$dir = scandir($dirPath);
foreach($dir as $index => &$item)
{
if(is_dir($dirPath. '/' . $item))
{
unset($dir[$index]);
}
}
$dir = array_values($dir);

check for files with PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get the Files inside a directory
Is there a function that can be used to get the contents of a directory (a photo gallery directory for example) ?
I'm trying to save time on a project by automating a photo gallery based on which files are available.
Thanks
Shane
You can either use the DirectoryIterator:
$dir = new DirectoryIterator('path/to/images');
foreach ($dir as $fileinfo) {
echo $fileinfo->getFilename() . "\n";
}
or alternatively glob():
$filenames = glob('path/to/images/*.jpg');
foreach ($filenames as $filename) {
echo $filename ."\n";
}
glob()
scandir()
I use a while loop to grab a list of files, omit the 2nd if statement if you want to grab a all files.
if ($handle = opendir('/photos/')) {
while(false !== ($sFile = readdir($handle))) {
if (strrpos($sFile, ".jpg") === strlen($sFile)-strlen(".jpg")) {
$fileList[] = $sfile;
}
}
}

Categories