How to put the files of a folder in an array? - php

In a folder "images" I have a thousand xml files.Those filenames I want them to be insert into an array
$images = array('','');
Instead of writing them all by hand, and this folder will be updated often, how can I do it automatically ?

Just exclude the . and .. entries if you don't want them:
$files = array_diff( scandir($dir), array('.','..') );

. and .. are always present in ALL directories ('current directory' and 'parent directory', respectively). You have to specifically filter them out. However, since you want only images, you could use something like glob() to just fetch images using regular shell wildcard patterns, e.g.
$files = glob('*.jpg');
which would give you all the files whose names end in .jpg.

Related

Filtering filenames in PHP

I'm trying to group a bunch of files together based on RecipeID and StepID. Instead of storing all of the filenames in a table I've decided to just use glob to get the images for the requested recipe. I feel like this will be more efficient and less data handling. Keeping in mind the directory will eventually contain many thousands of images. If I'm wrong about this then the below question is not necessary lol
So let's say I have RecipeID #5 (nachos, mmmm) and it has 3 preparation steps. The naming convention I've decided on would be as such:
5_1_getchips.jpg
5_2_laycheese.jpg
5_2_laytomatos.jpg
5_2_laysalsa.jpg
5_3_bake.jpg
5_finishednachos.jpg
5_morefinishedproduct.jpg
The files may be generated by a camera, so DSC###.jpg...or the person may have actually named each picture as I have above. Multiple images can exist per step. I'm not sure how I'll handle dupe filenames, but I feel that's out of scope.
I want to get all of the "5_" images...but filter them by all the ones that DON'T have any step # (grouped in one DIV), and then get all the ones that DO have a step (grouped in their respective DIVs).
I'm thinking of something like
foreach ( glob( $IMAGES_RECIPE . $RecipeID . "-*.*") as $image)
and then using a substr to filter out the step# but I'm concerned about getting the logic right because what if the original filename already has _#_ in it for some reason. Maybe I need to have a strict naming convention that always includes _0_ if it doesn't belong to a step.
Thoughts?
Globbing through 1000s of files will never being faster than having indexed those files in a database (of whatever type) and execute a database query for them. That's what databases are meant for.
I had a similar issue with 15,000 mp3 songs.
In the Win command line dir
dir *.mp3 /b /s > mp3.bat
Used a regex search and replace in NotePad++ that converted the the file names and prefixed and appended text creating a Rename statement and Ran the mp3.bat.
Something like this might work for you in PHP:
Use regex to extract the digits using preg_replace to
Create a logic table(s) to create the words for the new file names
create the new filename with rename()
Here is some simplified and UNTESTED Example code to show what I am suggesting.
Example Logic Table:
$translation[x][y][z] = "phrase";
$translation[x][y][z] = "phrase";
$translation[x][y][z] = "phrase";
$translation[x][y][z] = "phrase";
$folder = '/home/user/public_html/recipies/';
$dir=opendir($folder);
while (false !== ($found=readdir($dir))){
if pathinfo($file,PATHINFO_EXTENSION) == '.jpg')
{
$files[]= pathinfo($file,PATHINFO_FILENAME);
}
}
foreach($files as $key=> $filename){
$digit1 = 'DSC(\d)\d\d\.jpg/',"$1", $filename);
$digit2 = 'DSC\d(\d)\d\.jpg',"$1", $filename);
$digit3 = 'DSC\d\d(\d)\.jpg',"$1", $filename);
$newName = $translation[$digit1][$digit2][$digit3]
ren($filename,$newfilename);
}

Rename Many Files in a Folder - PHP

I have 2500 images in a Folder, which has NAME word in all the images. For examples
Peter Wang B5357550.jpg
Sander Mackiney B5355624.jpg
what i need to do is read all the filenames and rename it to the following
B5357550.jpg
B5355624.jpg
So remove NAME and SURNAME from filename, is it possible in PHP to do bulk renaming ?
(All student IDs are in format of Bxxxxxxx)
Quick, simple solution:
$dir = $_SERVER['DOCUMENT_ROOT'].'/your-folder-to-files';
$files = scandir($dir);
unset($files[0],$files[1]);
foreach ($files as $oldname){
$newname = substr($oldname, -12);
rename ($dir.'/'.$oldname, $dir.'/'.$newname);
}
N.B.: You may need to change the server path to something similar to:
$dir = "/home/users/you/folder_files/";
or
$dir = "folder_files/";
If $_SERVER['DOCUMENT_ROOT'] does not work for you.
If they're all in that format, it would be simple to fix, yes. Run glob to get all the .jpg files into an array, then simply explode the filename on spaces, use a foreach loop on that array, use end to get the last section, and rename the file to that string.

Using 'glob' to display files with no extension?

I am using the following code to display the files in descending order of date. But When I upload any file without extension its not visible because of glob, is there any way to show the hidden files?
Code:
<?php
$dir = "/opt/lampp/htdocs/jquery";
chdir($dir);
array_multisort(array_map('filemtime', ($files = glob("*.*"))), SORT_DESC, $files);
foreach($files as $filename)
{
echo "<li>".$filename."</li>";
}
?>
#bodi0 gave you the code for ONLY items with no dots, you might be looking for
...glob("*")
to get all files.
Then, you will need to remove "." and ".."
This is impossible with inclusive only glob (python), the answerers (is that a word), misunderstood your question.
/* gets all files/folders and returns folders with no "/" at the end, /*/ gets only folders and adds the "/" at the end, but for files with NO extension ie path/foo (NO DOT) it is not straightforward to separate the files from the folders with glob.
It is possible, of course, just pass this regex pattern to the glob():
glob("([^\.])");
The pattern ([^\.]) means every file name, which does not have a dot in it.

PHP - find all all files within directory that match certain string and put in array

I have a directory of images on a server that customers have uploaded. I need to be able to get all files that match a certain string or item code and put them inside an array. Filenames and extensions can always vary but each file will always have an 8 digit item code in the filename. So for instance say in my directory i have:
/images/
62115465.jpg
62115465-02.jpg
62115465-07.jpg
13452766.png
56773392.jpeg
56773392-avatar.jpg
I want to be able to pull out all the files that match the 8 digit item code so:
//all images that have 62115465 in the file name would give me
62115465.jpg
62115465-02.jpg
62115465-07.jpg
//or all images that have 56773392 in the file name would give me
56773392.jpeg
56773392-avatar.jpg
and then want them in an array like so:
$all_files = array(
'62115465.jpg',
'62115465-02.jpg',
'62115465-07.jpg'
);
I tried using the glob() function as below which can match some files like the 62115465.jpg but doesnt pick up the 2 other files with the -02 and -07 tags
$files = glob('62115465.'.*');
glob('62115465*');
note the removal of the .. glob() essentially replicates doing something like dir *.txt at a command prompt.
I know this question was answered already, but to the novice/intermediate coder, or anyone new to the glob() function (AHEM ME COUGH), it's pretty unclear what's going on here. So, here's a full script that I cobbled together to do pretty much the same thing the OP asked for- search through a directory for all files beginning with the target prefix and add them to an array.:
<?php
$imgs = array();
$dir = $_SERVER['DOCUMENT_ROOT'].'/path/to/your/images';
$prefix = 'your-prefix_string-_-';
chdir($dir);
$matches = glob("$prefix*");
if(is_array($matches) && !empty($matches)){
foreach($matches as $match){
$imgs[] = $match;
}
}
?>
Can you try this,
$files = glob('62115465.*');
Try like this-
$files = glob("[^62115465]*.*);
Or like this:
$files = glob("62115465*.*);

PHP - Open or copy a file when knowing only part of its name?

I have a huge repository of files that are ordered by numbered folders. In each folder is a file which starts with a unique number then an unknown string of characters. Given the unique number how can i open or copy this file?
for example:
I have been given the number '7656875' and nothing more.
I need to interact with a file called '\server\7656800\7656875 foobar 2x4'.
how can i achieve this using PHP?
If you know the directory name, consider using glob()
$matches = glob('./server/dir/'.$num.'*');
Then if there is only one file that should start with the number, take the first (and only) match.
Like Yacoby suggested, glob should do the trick. You can have multiple placeholders in it as well, so if you know the depth, but not the correct naming, you can do:
$matchingFiles = glob('/server/*/7656875*');
which would match
"/server/12345/7656875 foo.txt"
"/server/56789/7656875 bar.jpg"
but not
"/server/12345/subdir/7656875 foo.txt"
If you do not know the depth glob() won't help, you can use a RecursiveDirectoryIterator passing in the top most folder path, e.g.
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/server'));
foreach($iterator as $fileObject) {
// assuming the filename begins with the number
if(strpos($fileObject->getFilename(), '7656875') === 0) {
// do something with the $fileObject, e.g.
copy($fileObject->getPathname(), '/somewhere/else');
echo $fileObject->openFile()->fpassthru();
}
}
* Note: code is untested but should work
DirectoryIterator return SplFileInfo objects, so you can use them to directly access the files through a high-level API.
$result = system("ls \server\" . $specialNumber . '\');
$fh = fopen($result, 'r');
If it's hidden below in sub-sub-directories of variable length, use find
echo `find . -name "*$input*"`;
Explode and trim each result, then hope you found the correct one.

Categories