get all file names from a directory in php - php

(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)
}

Related

Optimising php file reading code

I have the following which is fairly slow. How can I speed it up?
(it scans a directory and makes headers out of the foldernames and retrieves the pdf files from within and adds them to lists)
$directories= array_diff(scandir("../pdfArchive/subfolder", 0), array('..', '.'));
foreach ($directories as $v) {
echo "<h3>".$v."</h3>";
$current = array_diff(scandir("../pdfArchive/subfolder/".$v, 0), array('..', '.'));
echo "<ul style=\"list-style-image: url(/images/pdf.gif); margin-left: 20px;\">";
foreach ($current as $vone) {
echo "<li><a target=\"blank\" href=\"../pdfArchive/subfolder/".$vone."\">".str_replace(".pdf", "", $vone)."</a>";
echo "</li><br>";
}
echo "</ul>";
}
Don't use array_diff() to filter out current and parent directory, use something like DirectoryIterator or glob() and then test whether it's . or .. via an if statement
glob() has a flag that allows you to retrieve only directories for your loops
Profile your code to see exactly what lines/functions are executing slowly
I'm not sure how fast array_diff() is when the array is very large, isn't it faster to simply add a separate check and make sure that '.' and '..' is not the returned name?
Other than that, I can't see there being anything really wrong.
What did you test to consider the current approach slow?
Here is a snippet of code I use that I adapted from php.net. It is very basic and goes through a given directory and lists the files contained within.
// The # suppresses any errors, $dir is the directory path
if (($handle = #opendir($dir)) != FALSE) {
// Loop over directory contents
while (($file = readdir($handle)) !== FALSE) {
// We don't want the current directory (.) or parent (..)
if ($file != "." && $file != "..") {
var_dump($file);
if (!is_dir($dir . $file)) {
// $file is really a file
} else {
// $file is a directory
}
}
}
closedir($handle);
} else {
// Deal with it
}
You may adapt this further to recurse over subdirectories by using is_dir to identify folders as I have shown above.

How to sort a list of files build up with PHP opendir() and hide extensions?

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>

php sorted array and readfile not reading in order

I am trying to write a php function to save and then display comments on an article.
In my save.php, I am formulating the file with:
$file = "article1/comments/file".time().".txt";
Then using fwrite() to write to a directory.
In my index I have:
if ($handle = opendir('article1/comments')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files = array($file);
sort($files);
foreach($files as $comments){
echo "<div class='message'>";
readfile('article1/comments/'.$comments);
echo "&lt/div>";
}
}
}
closedir($handle);
}
For the most part this displays the comments in the correct order, but for some reason, some files are displaying out of order. Furthermore, if I change sort() to rsort(), there is no change in how they are displayed.
I presume this is because readfile() is not following the sorted array's order. So I am wondering for one, why readfile does not display the files in order from newest to oldest, and two, how can I make it display them correctly?
Thanks.
edit: I copied the directory of comments from the live site to my local xampp installation, and the comments are displayed in order locally, but using the same code on my site results in comments not being in order.
Take a look at DirectoryIterator, make sure to check 1st comment for DirectoryIterator's isFile() method, it should be enough to solve this question.
Try this:
$files = array();
if ($handle = opendir('article1/comments')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files[] = $file; //adding file to array
}
}
closedir($handle);
}
//if array is not empty-check (can go here)
if(count($files)>0) {
sort($files);
foreach($files as $comments){
echo "<div class='message'>";
readfile('article1/comments'.$comments);
echo "</div>";
}//~foreach
}//~if
Please, use any database for this stuff! Don't use files! This is not realy secure and has low performance

Is there an easy way to read filenames in a directory and add to an array?

I have a directory: Audio/ and in that will be mp3 files only. I'm wanting to automate the process of creating links to those files. Is there a way to read a directory and add filenames within that directory to an array?
It'd be doubly cool if we could do an associative array, and have the key be the file name minus the .mp3 tag.
Any ideas?
To elaborate: I actual have several Audio/ folders and each folder contains mp3s of a different event. The event details are being pulled from a database and populating a table. That's why I'm duplicating code, because right now in each Audio/ folder, I'm having to define the filenames for the download links and define the filenames for the mp3 player.
Thank you! This will greatly simplify my code as right now I'm repeating tons of code over and over!
The SPL way is with DirectoryIterator:
$files = array();
foreach (new DirectoryIterator('/path/to/files/') as $fileInfo) {
if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
$files[] = $fileInfo->getFilename();
}
And for completeness : you could use glob as well :
$files = array_filter(glob('/path/to/files/*'), 'is_file');
This will return all files (but not the folders), you can adapt it as needed.
To get just the filenames (instead of files with complete path), just add :
$files = array_map('basename', $files);
Yes: use scandir(). If you just want the name of the file without the extension, use basename() on each element in the array you received from scandir().
This should be able to do what you're looking for:
// Read files
$files = scandir($dirName);
// Filter out non-files ('.' or '..')
$files = array_filter($files, 'is_file');
// Create associative array ('filename' => 'filename.mp3')
$files = array_combine(array_map('basename', $files), $files);
Sure...I think this should work...
$files[] = array();
$dir = opendir("/path/to/Audio") or die("Unable to open folder");
while ($file = readdir($dir)) {
$cleanfile = basename($file);
$files[$cleanfile] = $file;
}
closedir($dir);
I imagine that should work...
$results = array();
$handler = opendir($directory);
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
$results[] = $file;
}
}
closedir($handler);
this should work, if you want any files to be excluded from the array, just add them to the if statement, same for file extensions

PHP, reading a folder - listing all items with checkboxes and delete them?

i wonder if theres a tutorial out there or you could give me a quick and simple approach how i could do the following task.
i have a folder on my server. i want to build a kind of cms where i can easily delete files from a folder. i know how to upload them, i already found a tutorial.
i think of simply running through all files, creating a list of them with a checkbox in front, selecting the checkbox and pressing a DELETE button.
is this a rather difficult task to get done? do you maybe kno any tutorial or something.
thank you very much!
Start with
List all files
<?php
// file_array() by Jamon Holmgren. Exclude files by putting them in the $exclude
// string separated by pipes. Returns an array with filenames as strings.
function file_array($path, $exclude = ".|..", $recursive = false) {
$path = rtrim($path, "/") . "/";
$folder_handle = opendir($path);
$exclude_array = explode("|", $exclude);
$result = array();
while(false !== ($filename = readdir($folder_handle))) {
if(!in_array(strtolower($filename), $exclude_array)) {
if(is_dir($path . $filename . "/")) {
if($recursive) $result[] = file_array($path, $exclude, true);
} else {
$result[] = $filename;
}
}
}
return $result;
}
?>
then create hyperlinks to the above files to a delete function like;
unlink('filename.jpg');

Categories