finding files in a dir - php

I have a directory with a lot of files inside:
pic_1_79879879879879879.jpg
pic_1_89798798789798789.jpg
pic_1_45646545646545646.jpg
pic_2_12345678213145646.jpg
pic_3_78974565646465645.jpg
etc...
I need to list only the pic_1_ files. Any idea how I can do?
Thanks in advance.

Use the glob() function
foreach (glob("directory/pic_1_*") as $filename) {
echo "$filename";
}
Just change directory in the glob call to the proper path.
This does it all in one shot versus grabbing the list of files and then filtering them.

The opend dir function will help you
$dir ="your path here";
$filetoread ="pic_1_";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (strpos($file,$filetoread) !== false)
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
good luck see php.net opendir

This is what glob() is for:
glob — Find pathnames matching a pattern
Example:
foreach (glob("pic_1*.jpg") as $file)
{
echo $file;
}

Use scandir to list all the files in a directory and then use preg_grep to get the list of files which match the pattern you are looking for.

This is one of the samples from the manual
http://nz.php.net/manual/en/function.readdir.php
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
you can modify that code to test the filename to see if it starts with pic_1_
using something like this
if (substr($file, 0, 6) == 'pic_1_')
Manual reference for substr
http://nz.php.net/manual/en/function.substr.php

Related

List files with php

I'd like to know how to listing files with php?
What I try to do is it was sailing along this list of files in order that when it chooses one of them (.html) it me appears in the iframe that I have in my (index.php). Can someone help me?
use the below code:
$path = 'path to the directory';
$files = scandir($path);
I hope this helps you.
You can use readdir link to readdir
Look at this exemple:
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}

Making download links out of all of the files in a particular folder

Right now there is an upload system on the site I am working on where users can upload some documents to a particular file. Later on I will need to make these documents downloadable. Is there an easy way to iterate through all the files in a particular directory and create download links for the files?
Something like:
foreach($file){
echo 'somefilename';
}
Many thanks in advance.
if($dh = opendir('path/to/directory')) {
while(($file = readdir($dh)) !== false) {
if($file == "." || $file == "..") { continue; }
echo '' . $file . '';
}
closedir($dh);
}
You should see opendir.
Example from that page adapted to question:
$dir = "/etc/php5/";
$path = "/webpath";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "$file";
}
closedir($dh);
}
}

php readdir and is_dir

I am testing out the functions of directory handling. I have a fold/directory that contains the following:
0 File folder
false File folder
my_pictures File folder
MVI_3094 mov file
img01 jpeg image
etc...
I wrote the following code to traverse the directory and print out specific resutls
$handle = opendir("files/");
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
if(is_dir($entry))
{
echo "Directory:$entry<br />";
}
}
My only problem is that the second "if" statement does not output the results of
echo "Directory:$entry<br />";
even though the entry is a directory. I have checked the entry manually with the "var_dump" function and it returns true as a directory.
Any suggestions would help
Try this and check. Just a try...
$handle = opendir("files/");
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
elseif(is_dir("files/".$entry))
{
echo "Directory:$entry<br />";
}
}
$entry is relative... is_dir expects an absolute path.
Try:
if(is_dir("files/".$entry))
readdir() is just returning the filenames. Your code is therefore looking for the files in the current directory rather than the subdirectory.
This will just probe the basename of whatever directory entry:
is_dir($entry)
The opendir() result list will be relative to the directory you gave for reading. So you need to use:
is_dir("files/$entry")
Your problem is that in elseif(is_dir($entry)) {, entry is equal to some string like "file.txt" or "somedirectory", which isn't a path pointing to a file at all. It needs to be "files/file.txt".
Try this:
$dir = "files/";
$handle = opendir($dir);
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
if(is_dir($dir.$entry))
{
echo "Directory:$entry<br />";
}
}
Try using the DirectoryIterator:
$iterator = new \DirectoryIterator(realpath('files/'));
foreach($iterator as $file){
if($file->isDot())
continue;
if($file->isDir())
printf('Directory: %s <br/>', $file->getRealPath());
}

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

is_dir does not recognize folders

I am trying to make a function that scans a folder for subfolders and then returns
a numeric array with the names of those folders.
This is the code i use for testing. Once i get it to print out the folder names and not just "." and ".." for present and above folder all will be well, and I can finish the function.
<?php
function super_l_getthemes($dir="themes")
{
if ($handle = opendir($dir)) {
echo "Handle: {$handle}\n";
echo "Files:\n";
while (false !== ($file = readdir($handle))) {
echo "{$file}<br>";
}
closedir($handle);
}
?>
The above code works fine, and prints out all the contents of the folder: files, subfolders and the "." and ".."
but if i replace:
while (false !== ($file = readdir($handle))) {
echo "{$file}<br>";
}
with:
while (false !== ($file = readdir($handle))) {
if(file_exists($file) && is_dir($file)){echo "{$file}";}
}
The function only prints "." and ".." , not the two folder names that I'd like it to print.
Any help is appreciated.
You must provide the absolute path to file_exists, otherwise it will look for it in the current execution path.
while (false !== ($file = readdir($handle))) {
$file_path = $dir . DIRECTORY_SEPARATOR . $file;
if (file_exists($file_path) && is_dir($file_path)) {
echo "{$file}";
}
}
The problem with readdir is that it only reads the strings of the named entries inside of the directory.
For instance, if you had file "foo" inside of directory "/path/to/files/", when using readdir on "/path/to/files/", you would eventually come to the string "foo".
Normally this wouldn't be a problem if it were in the same directory as the current working directory of the script, but, since you are reading from an arbitrary director, when you are attempting to inspect the entry (file, directory, whatever), you are calling is_dir on the bare string "foo".
I would try prefixing the name you pull out using readdir with the path to the file.
if ($handle = opendir($dir)) {
echo "Handle: {$handle}\n";
echo "Files:\n";
while ($file = readdir($handle)) {
/*** make $file into an absolute path ***/
$absolute_path = $dir . '/' . $file;
/*** NOW try stat'ing it ***/
if (is_dir($absolute_path)) {
/* it's a directory; do stuff */
}
}
closedir($handle);
}
You need to use:
while (false !== ($file = readdir($handle))) {
if(file_exists($dir.'/'.$file) && is_dir($dir.'/'.$file)){echo "{$file}";}
}
See http://php.net/readdir
If you only want the directories of the starting folder, you can simply do:
glob('/some/path/to/search/in/*', GLOB_ONLYDIR);
which would given you only those foldernames in an array. If you want all directories below a given path, try SPL's RecursiveDirectoryIterator
$fileSystemIterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/some/path/to/look/in'),
RecursiveIteratorIterator::SELF_FIRST);
Iterators can be used with foreach:
$directories = array();
foreach($fileSystemIterator as $path => $fileSystemObject) {
if($fileSystemObject->isDir()) {
$directories[] = $path;
}
}
You will then have an array $directories with all directories under the given path.
$files = array();
foreach(new DirectoryIteraror('/path') as $file){
if($file->isDir() /* && !$file->isDot()*/) $files[] = $file->getFilename();
}
[edit: though you wanted to skip the dot, commented it out)
I don't think you need both file_exists and is_dir,
You just need the is_dir function. From the manual:
is_dir Returns TRUE if the filename exists and is a directory, FALSE otherwise.
Use this:
while (false !== ($file = readdir($handle))) {
if(is_dir($file)){echo "{$file}";}
}
is_dir will also check whether it's a relative path or an absolute path.
$directory = scandir($path);
foreach($directory as $a){
if(is_dir($path.$a.'/') && $a != '.' && $a != '..'){
echo $a.'<br/>';
}
}
With the path given as shown, it displays the folders present in the path.
I agree with nuqqsa's solution, however, I'd like to add something to it.
Instead of specifying the path, you can change the current directory instead.
For example,
// open directory handle
// ....
chdir($dir);
while (false !== ($file = readdir($handle)))
if(is_dir($file))
echo $file;
// close directory handle

Categories