Require to display limited number of file names from directories -php - php

For the below code I have multiple directories and files. I can display one filename per directory(Which is good with the "BREAK").
<?php
$dir = "/images/";
$i=0;
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
break;
//---- if ($i>=5) { break; }
}
closedir($dh);
}
}
?>
With
if ($i>=5) { break; } I can still display 5 filenames but it reads only one directory.
I want to display at least 5 file names from all directories, how can I do it?

Use the scandir function.
array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )
or
If you are using unix you could also do a system call and run the following command.
ls /$dir | head -5
$dir is the directory and -5 is the number filenames in the directory.

Since you said that you have multiple directory's, I rewrote your code a bit:
(Here I first loop through all directory's with array_map() then I get all files from each directory with glob(). After this I just limit the files per directory with array_slice() and at the end I simply print all file names)
<?php
$directorys = ["images/", "xy/"];
$limit = 3;
//get all files
$files = array_map(function($v){
return glob("$v*.*");
}, $directorys);
//limit files per directory
$files = array_map(function($v)use($limit){
return array_slice($v, 0, $limit);
}, $files);
foreach($files as $directory) {
echo "<b>Directory</b><br>";
foreach($directory as $file)
echo "$file<br>";
echo "<br><br>";
}
?>

You don't have to break it, you can just skip it. And in doing so, you have to use continue instead.
$dir = "/images/";
$i=0;
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
if ($i>=5)
continue;
}
closedir($dh);
}
}
Here is also another scenario. Because you mentioned that you have many directories but you only show one main directory, I am guessing that the directories you've mentioned were inside the /images/ directory.
$dir = "images/";
$i=1;
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
$j=1;
if (is_dir($file)) {
if ($internalDir = opendir($file)) {
while (($internalFile = readdir($internalDir)) !== false) {
echo $file."->filename: ".$internalFile."<br>";
if ($j>=5)
continue;
$j++;
}
closedir(opendir($file));
}
} else {
echo "filename:" . $file . "<br>";
if ($i>=5)
continue;
$i++;
}
}
closedir($dh);
}
}
Read more about continue here: http://php.net/manual/en/control-structures.continue.php

Related

how can i return the names of files in a directory using php

lets say I have a folder on a webhost that is called sebis_files and this folder contains some files, maybe pictures, docs...
I want to return the contents of this folder on a separate page, something like:
$row = get dir host/sebis_files*//everything
for ( $row !== 0){ //for every valid file
echo $row . "<br/>"; //return name of file
}
You can use opendir and readdir. Here's a breakdown:
We use __DIR__ to make the path relative to the directory of the current script, just to be safe:
$dir = __DIR__ . '/sebis_files';
Next we open the directory to read it's entries.
We call readdir, which will return a 'resource' object, or false if $dir is not a readable directory:
if ($dh = opendir($dir))
{
The directory is successfully opened.
We now call readdir on that directory. We use the return value of opendir, the mysterious 'resource' object, that will let PHP know what directory we are reading.
Every time we call readdir it will give us the next entry in the directory. When there are no more entries, readdir will return false:
while ( ($entry = readdir($dh)) !== false)
{
We have read a directory $entry: the name of a file or sub-directory inside $dir. So, it's not a full pathname. Let's print it's name, along with whether it is a directory or a file. We will use is_file and is_dir, but we will need to pass the full pathname (hence "$dir/$entry"):
if ( is_dir( "$dir/$entry" ) )
echo "Directory: $entry<br/>";
else if ( is_file( "$dir/entry" ) )
echo "File: $entry<br/>";
}
we are done with the directory, let's close it to free the resource:
closedir($dh);
}
But what if $dir cannot be opened for reading? Let's print a warning:
else
echo "<div class='warning'>cannot open directory!</div>";
you need is to see this
<?php
$dir = "/tmp";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
sort($files);
print_r($files);
rsort($files);
print_r($files);
?>
You can do it using the glob function :
$dir = "/your/dir/";
if(file_exists($dir))
{
foreach (glob("$dir*") as $file)
{
if(is_file($file))
{
echo basename($file) . "<br />";
}
}
}

Echo all the folder names in a folder

I want to print all the folder names inside a parent folder. The current issue I am facing is, though I have 400+ folders in a folder only 257 are getting printed. Again, this is not at all issue related with permissions.
Please find my code below:
$newdir = "content/";
$dircnt = 0;
// Open a known directory, and proceed to read its contents
if (is_dir($newdir)) {
if ($dh = opendir($newdir)) {
while (($file = readdir($dh)) !== false) {
$dircnt++;
if(filetype($newdir. $file) == 'dir') {
echo "filename: $file : filetype: " . filetype($newdir. $file) . "dircnt:" .$dircnt. "<br>";
}
}
closedir($dh);
}
}
}
You can use glob() function - returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
$filesDirectories = glob($newdir.'*', GLOB_BRACE);
foreach($filesDirectories as $key=>$file) {
echo "$file size " . filesize($file) . "\n";
}
I would use glob:
$newdir = "content/";
$dirs = glob($newdir.'*',GLOB_ONLYDIR);
foreach($dirs as $index=>$dir){
echo "filename ". $dir." filetype ".filetype($newdir.$dir)." dircnt:".($index+1)."<br/>";
}

read files insert text into mysql

myFolderi have thousands of image files that have keyword text for the name. i am trying to read from the list of images and upload the text into a dB field. the problem is that some of the text has utf8 characters like l’Été that show up like this ��t�
how can i read foreign characters so that the accents will insert into the dB field?
this is how im handling it now
function ListFiles($dir) {
if($dh = opendir($dir)) {
$files = Array();
$inner_files = Array();
while($file = readdir($dh)) {
if($file != "." && $file != ".." && $file[0] != '.') {
if(is_dir($dir . "/" . $file)) {
$inner_files = ListFiles($dir . "/" . $file);
if(is_array($inner_files)) $files = array_merge($files, $inner_files);
} else {
array_push($files, $dir . "/" . $file);//$dir = directory name
//array_push($files, $dir);
}
}
}
closedir($dh);
return $files;
}
}
foreach (ListFiles('../../myDirectory') as $key=>$file){
//$file = preg_replace( '#[^\0-\x80]#u',"", $file );
echo $file ."<br />";
}
this is producing the same result
$str = "l’Été";
utf8_decode($str);
echo $str;
This solution may work for you, it will loop through all files in a directoy and then recursivly through any directories found until it ends up with a massive array of files.
Ive added some points you may wish to change, eg either mutli or single dimension arrays ( all depend on if you may want to maintain the folder structure.
and also if you want the file extention to be saved when you save the file name to db.
Code
function recursive_search_dir($dir) {
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (in_array($file,array(".","..")))
continue; // We dont want to do anything with parent / current directory.
if (is_dir($file)) {
$result[] = recursive_search_dir($file); // Multi-dimension
# OR
array_merge($result,recursive_search_dir($file));// Single-dimension if you dont care about folder structure.
} else {
$result[] = utf8_decode($file); // full file name ( includes extention )
# OR
$result[] = utf8_decode(filename($file,PATHINFO_FILENAME)); // if you only want to capture the name and not the extention.
}
}
closedir($handle);
}
return $result;
}
$files = recursive_search_dir("."); // recursively searcht the current directory.

How to get the file name under a folder?

Suppose I have a directory look like:
ABC
|_ a1.txt
|_ a2.txt
|_ a3.txt
|_ a4.txt
|_ a5.txt
How can I use PHP to get these file names to an array, limited to a specific file extension and ignoring directories?
You can use the glob() function:
Example 01:
<?php
// read all files inside the given directory
// limited to a specific file extension
$files = glob("./ABC/*.txt");
?>
Example 02:
<?php
// perform actions for each file found
foreach (glob("./ABC/*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
Example 03: Using RecursiveIteratorIterator
<?php
foreach(new RecursiveIteratorIterator( new RecursiveDirectoryIterator("../")) as $file) {
if (strtolower(substr($file, -4)) == ".txt") {
echo $file;
}
}
?>
Try this:
if ($handle = opendir('.')) {
$files=array();
while (false !== ($file = readdir($handle))) {
if(is_file($file)){
$files[]=$file;
}
}
closedir($handle);
}
scandir lists files and directories inside the specified path.
Here is the most Efficient way based on this article's benchmarks:
function getAllFiles() {
$files = array();
$dir = opendir('/ABC/');
while (($currentFile = readdir($dir)) !== false) {
if (endsWith($currentFile, '.txt'))
$files[] = $currentFile;
}
closedir($dir);
return $files;
}
function endsWith($haystack, $needle) {
return substr($haystack, -strlen($needle)) == $needle;
}
just use the getAllFiles() function, and you can even modify it to take the folder path and/or the extensions needed, it is easy.
Aside from scandir (#miku), you might also find glob interesting for wildcard matching.
If your text files is all that you have inside of the folder, the simplest way is to use scandir, like this:
<?php
$arr=scandir('ABC/');
?>
If you have other files, you should use glob as in Lawrence's answer.
$dir = "your folder url"; //give only url, it shows all folder data
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != '.' and $file != '..'){
echo $file .'<br>';
}
}
closedir($dh);
}
}
output:
xyz
abc
2017
motopress

Display contents of multiple text files

I have a number of text files held in directory
/results/...
All the text files are named with unixtime stamps, inside each of the following files there is:
#text¬test¬test1¬test2¬test3¬test4¬1262384177
Each piece of text is seperated by '¬'.
I'd then like to feed the contents of the text file into an array and output it, in for example a table, but for each of the files (Perhaps loop-like?)
If have this but it only works for one file and fixed file name:
$filename = "results/unixtime.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$array01 = explode("¬",$contents);
$count = count($array01);
echo "<table width = 500 border=1 cellpadding=4>";
$i=0;
for ($i=0;$i<$count;$i++) {
echo "<tr><td>";
echo $array01[$i];
echo "</td></tr>";
}
echo "</table>";
I suggest the fairly-unknown glob function to detect all your files. Then with all the filenames in a handy array, just iterate through and open up/read each one. Sort of like this:
$files = glob('*.txt');
while(list($i, $filename) = each($files)){
//what you have now
}
A couple of things:
Unless you're dealing with really large files just use file_get_contents() to load files. It's a one-liner versus three lines of code that you just don't need;
Loop over arrays using foreach unless you explicitly need a loop counter. The loop condnition/counter is just another area where you can make simple errors;
Use opendir(), readdir() and closedir() for reading directory contents; and
Directories will contain entries like "." and "..". Use filetype() and/or a check on the name and/or extension to limit it to the files you're interested in.
Example:
$directory = "results/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
$items = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
foreach ($items as $item) {
echo "<tr><td>$item</td></tr>\n";
}
echo '</table>';
}
}
closedir($dir);
You can get all the files located in "result" via opendir.
There is also an example ...
<?php
$dir = "/etc/php5/";
// 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 : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
Grab the files in the directory and read each filename.
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$filename = $file;
//your code
}
}
closedir($handle);
}
?>
source: http://php.net/manual/en/function.readdir.php
Here is a more elegant way of writing brianreavis solution, also use file_get_contents instead of fopen, fread and fclose, it's faster and less verbose.
foreach (glob('*.txt') as $filename)
{
$contents = file_get_contents($filename);
}
Use this code, replace DOCROOT with directory you want to scan.
foreach (scandir(DOCROOT.'css') as $dir) {
echo $dir . "<br>";
echo file_get_contents(DOCROOT . 'css/' . $dir ) . "<hr />";
}

Categories