How can I search a specific directory and its subdirectories for a specific file?
What I've tried are the following two functions:
function getImageDirectory($ipaPath) {
$oDirectory = new RecursiveDirectoryIterator($ipaPath);
$oIterator = new RecursiveIteratorIterator($oDirectory);
foreach($oIterator as $oFile) {
if ($oFile->getFilename() == 'info.plist') {
return $oFile->getPath();
}
}
}
EDIT: This one works, just as well as the answer bellow! My example above return the directory of the file you are looking for, in this case "info.plist".
EDIT2: Thanks for the down votes! If someone would have asked a similar question it would have shown when I wrote the title. But nothing for PHP. So if I search for the wrong thing, not using developer language it shouldn't be down voted! And now someone with my low php skills might find an answer to this question! Is stackoverflow only for PRO's or for anyone that needs help?
As #diEcho suggested, use glob.
Get file list like this:
<?php
foreach( glob( "*.*" ) as $filename ) {
echo "$filename size " . filesize( $filename ) . "\n";
}
?>
After that, just go through the results. You might need a recursive function, to access subfolders though.
Related
I came up with this questioin. My background is from the Node.js. I am not usually quite used to be in PHP. That's why I'm aksing this question to solve the current issues.
The issues is that's to says I have certain Files and Folders that contains with a specific letters and number at the beginning. As you can see given by down below with a scrrenshot.
I just learn and writing some php code that I grabbed it from the internet resources. Take a look at what's my code:
I want this to detele this all folders which contains letters "exp_" and all the files names start with this numbers "xx-xx-xx" etc.
I created delete.php. When I'd called this file via the browser, I want to achieve to delete all the files and folder which for the No. 1 case.
All these folders and files are generated in everdays. That's why I do want to clean all those data.
<?php
$path = "test";
if(!unlink($path)){
echo "File has not deleted yet.";
} else {
echo "Successfully deleted!";
}
?>
Is there any how any solution to solve this issues? I will appreciate all in advanced who are giving me idea and suggestions from you guys.
You can do something like this:
$files = new DirectoryIterator(__DIR__);
foreach ($files as $file) {
if ( ($file->isDir() and strpos($file->getFilename(),'exp_')!==false) || ($file->isFile() and $file->getFilename() == date('d-m-Y') ) ) {
unlink($file->getPathname());
}
}
Thus, all folders with names like exp_ and files with today's date will be deleted.
I have a list of PDFs and I would like to delete them. Can someone please explain to a beginner how this is done? At this point, I can do this in Excel a number of different ways but how can I simply do this in PHP?
Most simple solution:
<?php
$dir = '/files_directory/';
$files_to_delete = array('file1.pdf', 'file3.pdf', 'file4.pdf');
foreach($files_to_delete as $file)
{
$file_path = $dir . $file;
if(is_file($file_path))
{
unlink($file_path);
}
}
Use PHP to search for the folder, do a loop through the files there and add some conditional statements to the loop. If they are true or false, act on those results.
As you have not typed any code for us, I am not going to type any code back to you.
The most simple way I could think of doing it:
array_map('unlink', $array_with_files_to_delete);
$array_with_files_to_keep = array_diff($list_with_pdfs, $array_with_files_to_delete);
I have two folders, in one i have the videos and in the second one the configuration files for each video(3 files per video). Now if i want to delete a video i have to delete files by hand.
I found this :
<?php
$filename = 'name.of.the.video.xml';
$term = str_replace(".xml","", $filename);
$dirPath = ("D:/test/");
foreach (glob($dirPath.$term.".*") as $removeFile)
{
unlink ($removeFile);
}
?>
A echo will return:
D:/test/name.of.the.video.jpg
D:/test/name.of.the.video.srt
D:/test/name.of.the.video.xml
Is ok and it help me a lot, but i have a problem here.
Not all files are the same ex:
Name.of.The.video.jpg
Name.Of.The.Video.xml
If i echo the folder looking for that string and is not identic with the $filename will return empty.
So, my question is, how can i make that search Case insensitive?
Thank you.
You are making use of the glob function which is case sensitive. You are using the wrong function therefore to get the list of files.
You should therefore first normalize the filenames in the directory so they all share the same case (e.g. all lowercase). Or you need to use another method to get the directory listing case-insensitive. I suggest the first, however if that is not an option, why don't you glob for all files first and then filter the list of files using preg_grep which allows to specify patterns that are case-insensitive?
Which leads me to the point that it's more practicable to use DirectoryIterator with a RegexIterator:
$filename = 'name.of.the.video.xml';
$term = basename($filename, ".xml");
$files = new DirectoryIterator($dirPath);
$filesFiltered = new RegexIterator($files, sprintf('(^%s\\..*$)i', preg_quote($term)));
foreach($filesFiltered as $file)
{
printf("delete: %s\n", $file);
unlink($file->getPathname());
}
A good example of the flexibility of the Iterators code are your changed requirements: Do that for two directories at once. You just create two DirectoryIterators and append the one to the other with an AppendIterator. Job done. The rest of the code stays the same:
...
$files = new AppendIterator();
$files->append(new DirectoryIterator($dirPath1));
$files->append(new DirectoryIterator($dirPath2));
...
Voilá. Sounds good? glob is okay for some quick jobs that need just it. For everything else with directory operations start to consider the SPL. It has much more power.
Is strcasecmp() a valid function for this? Its a case insensitive str comparison function?
Surely if you know the file name and you can echo it out, you can pass this to unlink()?
I'd like to make a gallery of all images i have under my domain (my internet root folder). All these images are in different folders. What's the best way to 'browse' through all the folders and return the images?
Use Google Image Search with site: www.mydomainwithimages.com as the search term and this will show you all your indexed images. This should be everything in your domain as long as your robots.txt file doesn't exclude the Google crawler.
Take a look at opendir you would want to write a function that gets called in a recursive loop, the function could loop through the files in the specific directory, check the file extension and return the files as an array which you would merge with a global array.
Depends on hosting system, you could use command line with exec or passthru
find /path/to/website/root/ -type f -name '*.jpg'
If you can't do such a thing, as fire said, opendir is the way to go.
I would give PHP's DirectoryIterator a spin.
This is untested pseudo-code, but it should work a little bit like this:
function scanDirectoryForImages($dirPath)
{
$images = array();
$dirIter = new DirectoryIterator($dirPath);
foreach($dirIter as $fileInfo)
{
if($fileInfo->isDot())
continue;
// If it's a directory, scan it recursively
elseif($fileInfo->isDir())
{
$images = array_merge(
$images, scanDirectoryForImages($fileInfo->getPath())
);
}
elseif($fileInfo->isFile())
{
/* This works only for JPEGs, oviously, but feel free to add other
extensions */
if(strpos($fileInfo->getFilename(), '.jpg') !== FALSE)
{
$images[] = $fileInfo->getPathname();
}
}
}
return $images;
}
Please don't sue me if this doesn't work, it's really kinda from the top of my hat, but using such a function would be the most elegant way to solve your problem, imho.
// edit: Yeah, that's basically the same as fire pointed out.
I'm trying to design a program in PHP that would allow me to find files with specific file extensions (example .jpg, .shp etc) in a known directory which consists of multiple folders.
Sample code, documentation or information about what methods I will be required to use will be much appreciated.
glob is pretty easy:
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
There are a few suggestions for recursive descent at the readdir page.
Take a look at PHP's SPL DirectoryIterator.
I believe PHP's glob() function is exactly what you are looking for:
http://php.net/manual/en/function.glob.php
Use readdir to get a list of files, and fnmatch to work out if it matches your required filename pattern. Do all this inside a function, and call your function when you find directories. Ask another question if you get stuck implementing this (or comment if you really have no idea where to start).
glob will get you all the files in a given directory, but not the sub directories. If you need that too, you will need to: 10. get recursive, 20. goto 10.
Here's the pseudo pseudocode:
function getFiles($pattern, $dir) {
$files = glob($dir . $pattern);
$folders = glob($dir, GLOB_ONLYDIR);
foreach ($folders as $folder) {
$files = $files + getFiles($folder);
}
return $files;
}
The above will obviously need to be tweaked to get it working, but hopefully you get the idea (remember not to follow directory links to ".." or "." or you'll be in infinite loop town).