Saqib
Saqib

Reputation: 1129

get all file names from a directory in 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;
    }
  }

Upvotes: 1

Views: 16252

Answers (5)

Mahdi Jazini
Mahdi Jazini

Reputation: 791

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

Upvotes: -1

MilMike
MilMike

Reputation: 12831

<?php
$files=glob("somefolder/*.*");
print_r($files);
?>

Upvotes: 3

Arxeiss
Arxeiss

Reputation: 1046

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

Upvotes: 1

Tim Withers
Tim Withers

Reputation: 12059

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.

Upvotes: 8

VoteyDisciple
VoteyDisciple

Reputation: 37803

Take a look at the Directory class (here) and readdir()

Upvotes: 1

Related Questions