Get all files in directory with specified extension with PHP? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP list of specific files in a directory
use php scandir($dir) and get only images!
So right now I have a directory and I am getting a list of files
$dir_f = "whatever/random/";
$files = scandir($dir_f);
That, however, retrieves every file in a directory. How would I retrive only files with a certain extension such as .ini in most efficient way.

PHP has a great function to help you capture only the files you need. Its called glob()
glob - Find pathnames matching a pattern
Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
Here is an example usage -
$files = glob("/path/to/folder/*.txt");
This will populate the $files variable with a list of all files matching the *.txt pattern in the given path.
Reference -
glob()

If you want more than one extension searched, then preg_grep() is an alternative for filtering:
$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f));
Though glob has a similar extra syntax. This mostly makes sense if you have further conditions, add the ~i flag for case-insensitive, or can filter combined lists.

PHP's glob() function let's you specify a pattern to search for.

You can try using GlobIterator
$iterator = new \GlobIterator(__DIR__ . '/*.txt', FilesystemIterator::KEY_AS_FILENAME);
$array = iterator_to_array($iterator);
var_dump($array);

glob($pattern, $flags)
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>

try this
//path to directory to scan
$directory = "../file/";
//get all image files with a .txt extension.
$file= glob($directory . "*.txt ");
//print each file name
foreach($file as $filew)
{
echo $filew;
$files[] = $filew; // to create the array
}

haven't tested the regex but something like this:
if ($handle = opendir('/file/path')) {
while (false !== ($entry = readdir($handle))) {
if (preg_match('/\.txt$/', $entry)) {
echo "$entry\n";
}
}
closedir($handle);
}

Related

Want regex for glob api to find files

My directory structure is like D:/dir1/dir2/project_dir/dir3/dir4/dir5/cache/all_files
So i want to get all the files under cache folder.
So i wrote
glob("project_dir/*/*/*/cache/*");
But cache folder is also there in dir3 or dir4 like
D:/dir1/dir2/project_dir/dir3/dir4/dir5/dir6/dir7/cache/all_files
or
D:/dir1/dir2/project_dir/dir3/cache/all_files
So can anyone give me the regex to get the files from 'cache' folder,
like
glob("project_dir/*/cache/*");
Btw, this is not working because it is searching for immediate directory after project_dir.
Thanks in advance.
Hope this helps!
Supports PHP 5 and 7 only,check your version before using this code
for more info refer : http://php.net/manual/en/class.directoryiterator.php
$searchCacheFolderUnder = 'D:\xampp\htdocs\mygit\\';
$pathOfAllCacheFolders = array();
$dir = new DirectoryIterator(realpath($searchCacheFolderUnder));
foreach ($dir as $fileInfo) {
if($fileInfo->isDir()) {
// optimize strpos with inbuild directory iterator methods
if( strpos($fileInfo->getPathname(), 'cache') !== false ){
$pathOfAllCacheFolders[] = $fileInfo->getPathname();
}
}
}
// contains all cache folders path
echo "<pre>";
print_r($pathOfAllCacheFolders);
echo "</pre>";
// loop on all cache folders
foreach($pathOfAllCacheFolders as $cachePath)
$dirCache = new DirectoryIterator(realpath($cachePath));
foreach ($dirCache as $fileInfo) {
//$fileInfo object will have everything you need
echo "<pre>";
print_r($fileInfo);
echo "</pre>";
}
You have to modify this code a bit to meet your requirement. Refer Directory Iterator for more available options.
You can use glob('*') but the only perk for using this is it ignores all hidden files. If you want all the files that includes hidden files in a folder then use:
$files = glob('project_dir/cache/{,.}*', GLOB_BRACE);
Remember this will return all the files for "." and "" and even the directory entries . and .. Let me know in case of any issues.
Hope this helps.

How can I check if a file exists with a certain string in its filename?

I'd like to be able to search a directory for a file that starts with a specific string, for example:
- foo
- 1_foo.jpg
- 2_bar.png
How would I check directory foo for files that begin with "1_"?
I've tried using file_exists and preg_match like so:
if (file_exists("foo/" . preg_match("/^1_/", "foo/*"))) echo "File exists.";
but this doesn't work.
Sounds like you need the glob() function. The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.
<?php
foreach (glob('1_*.*') as $filename) {
echo "$filename\n";
}
?>
The above example will output something similar to:
1_foo.png
1_bar.png
1_something.png
Sorry, but the filesystem doesn't understand wildcards or regular expressions. To accomplish what you want, you have to open the directory and read its contents, getting a list of all the files in that directory. Then you use standard string utilities to see which filenames match your criteria.
I think PHP's scandir is what you want as a starting point. You can also use glob but that actually forks a shell to get the file list (which in turn will do the C equivalent of scandir()).
You can use the glob() function
<?php
$list = glob('1_*.*');
var_dump($list);
I was having some trouble checking a directory and files and I gather some scripts here and there and this worked for me (Hope it helps u too):
if ($handle = opendir('path/to/folder/'))
{
while ( false !== ($entry = readdir($handle)) ) {
if ( $entry != "." && $entry != ".." ) {
// echo "$entry<br>";
if (preg_match("/^filename[0-9]_[0-9].jpg/", $entry))
{
// $found_it = TRUE;
}
}
}
closedir($handle);
}

Ordering output when using readdir()

I'm fairly new to PHP and have been using PHP's readdir() to look into a folder full of images and render them out dynamically based on how many images there are in that folder. Everything works great, but one thing I've noticed is that the images are not displayed in the order that they appear on my local machine HD.
So my question to anyone who knows PHP is, is there way of using PHP to read the contents of a folder AND display them in order without having to rename the actual file names e.g. 01.jpg, 02.jpg etc etc?
Have a look at the glob() function, it returns files alphabetically sorted by default:
$files = glob('/some/path/*.*');
Bonus, you can filter just images, and leave out directories.
readdir likely just takes the file system order. Which is alphabetical on NTFS, but seemingly random on most Unix filesystems. The documentation even says as much: »The entries are returned in the order in which they are stored by the filesystem.«
So you'd have to store the list in an array and sort that based on how you would like them to be sorted.
The php manual says:
string readdir ([ resource $dir_handle ] )
Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.
Meaning they should appear the same way.
More information found in the manual.
Why not apply one of the sort-functions of PHP?
$files = readdir( $theFoldersPath );
sort( $files );
Here is what I came up with in answer (together with the help of the people who posted) to my own question.
<?php
$dir = "low res";
$returnstr = "";
// The first part puts all the images into an array, which I can then sort using natsort()
$images = array();
if ($handle = opendir($dir)) {
while ( false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".."){
$images[] = $entry;
}
}
closedir($handle);
}
natsort($images);
print_r($images);
$newArray = array_values($images);
// This bit then outputs all the images in the folder along with it's own name
foreach ($newArray as $key => $value) {
// echo "$key - <strong>$value</strong> <br />";
$returnstr .= '<div class="imgWrapper">';
$returnstr .= '<div class="imgFrame"><img src="'. $dir . '/' . $value . '"/></div>';
$returnstr .= '<div class="imgName">' . $value . '</div>';
$returnstr .= '</div>';
}
echo $returnstr;
?>

PHP readir results - trying to sort by date created and also get rid of "." and ".."

I have a double question. Part one: I've pulled a nice list of pdf files from a directory and have appended a file called download.php to the "href" link so the pdf files don't try to open as a web page (they do save/save as instead). Trouble is I need to order the pdf files/links by date created. I've tried lots of variations but nothing seems to work! Script below. I'd also like to get rid of the "." and ".." directory dots! Any ideas on how to achieve all of that. Individually, these problems have been solved before, but not with my appended download.php scenario :)
<?php
$dir="../uploads2"; // Directory where files are stored
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
?>
<p><a href="http://www.duncton.org/download.php?file=login/uploads2/<?php echo $filename; ?>"><?php echo $filename;
?></a></p>
<?php
}
closedir($dir_list);
}
?>
While you can filter them out*, the . and .. handles always come first. So you could just cut them away. In particular if you use the simpler scandir() method:
foreach (array_slice(scandir($dir), 2) as $filename) {
One could also use glob("dir/*") which skips dotfiles implicitly. As it returns the full path sorting by ctime then becomes easier as well:
$files = glob("dir/*");
// make filename->ctime mapping
$files = array_combine($files, array_map("filectime", $files));
// sorts filename list
arsort($files);
$files = array_keys($files);

Best way to get files from a dir filtered by certain extension in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP list of specific files in a directory
use php scandir($dir) and get only images!
So right now I have a directory and I am getting a list of files
$dir_f = "whatever/random/";
$files = scandir($dir_f);
That, however, retrieves every file in a directory. How would I retrive only files with a certain extension such as .ini in most efficient way.
PHP has a great function to help you capture only the files you need. Its called glob()
glob - Find pathnames matching a pattern
Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
Here is an example usage -
$files = glob("/path/to/folder/*.txt");
This will populate the $files variable with a list of all files matching the *.txt pattern in the given path.
Reference -
glob()
If you want more than one extension searched, then preg_grep() is an alternative for filtering:
$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f));
Though glob has a similar extra syntax. This mostly makes sense if you have further conditions, add the ~i flag for case-insensitive, or can filter combined lists.
PHP's glob() function let's you specify a pattern to search for.
You can try using GlobIterator
$iterator = new \GlobIterator(__DIR__ . '/*.txt', FilesystemIterator::KEY_AS_FILENAME);
$array = iterator_to_array($iterator);
var_dump($array);
glob($pattern, $flags)
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
try this
//path to directory to scan
$directory = "../file/";
//get all image files with a .txt extension.
$file= glob($directory . "*.txt ");
//print each file name
foreach($file as $filew)
{
echo $filew;
$files[] = $filew; // to create the array
}
haven't tested the regex but something like this:
if ($handle = opendir('/file/path')) {
while (false !== ($entry = readdir($handle))) {
if (preg_match('/\.txt$/', $entry)) {
echo "$entry\n";
}
}
closedir($handle);
}

Categories