Rename Many Files in a Folder - PHP - 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.

Related

stripos vs glob for unlinking

I want to delete the files which are not appearing in this array. I know the name of file partially but don't know the size parameter suffixed after file name like filename-50x75.jpg, filename-100x77.jpg , filename-500x377.jpg.
I want to delete above images from a directory and don't want to delete below images.
$list_of_allowed_images=array("filename-50x50.jpg","filename-50x70.jpg","filename-90x50.jpg","filename-100x100.jpg","filename-150x150.jpg","filename-250x200.jpg","filename-300x250.jpg","filename-360x270.jpg","filename-390x250.jpg","filename-500x345.jpg","filename-768x576.jpg","filename-820x400.jpg","filename-1024x768.jpg");
I have the following snippet:
foreach(glob($base_path_del.$only_obs_img."[0-9][0-9]*x*.{jpg,gif,png}", GLOB_BRACE) as $file_to_del_now)
{
if(!in_array($file_to_del_now,$list_of_allowed_images))
{
unlink($file_to_del_now);
}
}
but I think it can be more efficient. Is another more efficient way to do this?
Here's what I recommend:
(untested code)
chdir($base_path_del);
$files = glob($only_obs_img."[0-9][0-9]*x*.{jpg,gif,png}", GLOB_BRACE);
$whitelist_regex = "/-(?:50x[57]0|90x50|100x100|150x150|250x200|300x250|360x270|390x250|500x345|768x576|820x400|1024x768)\.jpg$/i";
$removables = preg_grep($whitelist_regex, $files, PREG_GREP_INVERT);
foreach ($removables as $filename) {
unlink($filename);
}
So...
Change the current working directory so that glob() doesn't include the paths in the collection of qualifying files.
Invert preg_grep() so that files that don't match the whitelist regex requirements are retained.
Then just loop the naughty list and delete the lot.
The regex pattern boils down your whitelist array logic. The check starts at the last - in the filename, checks the dimensions, checks .jpg case-insensitively, then ensures that the filename has ended.
p.s. or array_map() if you don't want to break the functional style.
array_map('unlink', $removables);

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*.*);

Trim the text "th_" from variable and save the result to a new variable?

My question is quick and simple.
I am creating a gallery and I am fetching my full-size images and my thumbnails from a directory using glob.
I have a variable for the path to my thumbnail images : images/photo-strip/thumb/*.jpg
I am reducing the path images/photo-strip/thumb/*.jpg to *.jpg using basename() and I save that to $filename
Then I re-build the path to the full size image like this: $pathToFull = 'images/photo-strip/' . $filename;
My files inside the thumb folder are named like so: th_*.jpg and the full size images are *.jpg (exactly matching but without the th).
I then have an echo that puts the HTML, with thumbnail path in an <img> tag and fullsize path to an <a> tag.
Problem is the path to my full-size images is wrong because of the th_ in the filenames of the images.
Is there a way to trim the th_ from $filename and save it to something like $full_filename so I can correct the filename for the full-size images?
I could easily rename the thumbnail images to exclude th_ and this would solve my problem but I would prefer to leave the file names as is.
EDIT:
I am using BCMCFC's method as it get's rid of two lines of code that I don't neccessarily have to have.
Thanks for the speedy answers!
Instead of rebuilding the path, it sounds like you could simplify the process as follows:
$img = str_replace('images/photo-strip/thumb/th_', 'images/photo-strip/', $originalImage);
Or just:
$img = str_replace('thumb/th_', '', $originalImage);
Just use the str_replace function to replace "th_" by empty string
Look no further than $full_filename = substr($filename,3);
This would be the most elegant way to do it:-
$filename = 'th_myimage.jpg';
$pathToFull = 'images/photo-strip/' . preg_replace('/^(th_)?/', '', $filename);
// $filename would be 'myimage.jpg'
This regular expression pattern would replace only the first occurrence of th_ and if it was at the start of the string.
This has an implementation for batch renaming files in a directory.
Bulk Rename Files in a Folder - PHP
You could use "explode" to split the string on the "_" character to an array, then get the latter element of the array.
$myarray = explode("_", $filename);
if(count($myarray)>1){
$full_filename = $myarray[1];
}

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

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.

Categories