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());
}
}
?>
Related
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
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.
(Well what I gone through a lot of posts here on stackoverflow and other sites. I need a simple task, )
I want to provide my user facility to click on upload file from his account, then select a directory and get the list of all the files names inside that directory.
According to the posts here what I got is I have to pre-define the directory name, which I want to avoid.
Is there a simple way to click a directory and get all the files names in an array in PHP? many thanks in advance!
$dir = isset($_POST['uploadFile']) ? _SERVER['DOCUMENT_ROOT'].'/'.$_POST['uploadFile'] : null;
if ($_POST['uploadFile'] == true)
{
foreach (glob($dir."/*.mp3") as $filename) {
echo $filename;
}
}
I will go ahead and post a sample of code I am currently using, with a few changes, although I would normally tell you to look it up on google and try it first.
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo $file;
}
closedir($handle);
}
This will display the entire contents of a directory... including: ".", "..", any sub-directories, and any hidden files. I am sure you can figure out a way to hide those if it is not desirable.
<?php
$files=glob("somefolder/*.*");
print_r($files);
?>
Take a look at the Directory class (here) and readdir()
I'm confused what do you want, all files or only some files?
But if you want array of folders and files, do this
$folders = array();
$files = array();
$dir = opendir("path");
for($i=0;false !== ($file = readdir($dir));$i++){
if($file != "." and $file != ".."){
if(is_file($file)
$files[] = $file;
else
$folders[] = $file;
}
}
And if only some folders you want, later you can delete them from array
I always use this amazing code to get file lists:
$THE_PATTERN=$_SERVER["DOCUMENT_ROOT"]."/foldername/*.jpg";
$TheFilesList = #glob($THE_PATTERN);
$TheFilesTotal = #count($TheFilesList);
$TheFilesTotal = $TheFilesTotal - 1;
$TheFileTemp = "";
for ($TheFilex=0; $TheFilex<=$TheFilesTotal; $TheFilex++)
{
$TheFileTemp = $TheFilesList[$TheFilex];
echo $TheFileTemp . "<br>"; // here you can get full address of files (one by one)
}
As I only get one very very tiny part of the PHP phenomenon I'm very happy that I managed to create the following script by searching the web. As you can see, this shows the files present in the folder 'archive' on the website I'm building. It's for the newspaper of my school. The old papers will be uploaded to this folder. A problem is that the order is very messy at the moment. I know PHP can sort things with sort(), but I'm not sure how to do that in this case. Could anyone explain how to get it fixed?
Another thing is hiding the extensions. I couldn’t find it yet, is there a possibility for that?
You’d be a great help if you could help me at least with the first thing :)
<?php
if ($handle = opendir(archive)) {
$ignore_files = array('.', '..', '.htaccess', '.htpasswd', 'index.php');
while (false !== ($file = readdir($handle)))
{
if (!in_array($file, $ignore_files))
{
$thelist .= ''.$file.''.'<br>';
}
}
closedir($handle);
}
?>
<p><?=$thelist?></p>
If you want to get the list of files from a directory, (and then sort that list), also stripping off the extension, you would do this:
<?php
// $archive variabe assumed to point to '/archive' folder
$ignore_files = array('.', '..', '.htaccess', '.htpasswd', 'index.php');
// into array $files1 will be every file inside $archive:
$files1 = scandir($archive);
sort($files1);
foreach ($files1 as $file) {
if (!in_array($file, $ignore_files)) {
$fileParts = pathinfo($file);
$thelist .= ''.$fileParts['filename'].''.'<br>';
}
}
?>
<p><?=$thelist?></p>
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;
}
}
}