Php rename files using js file that contains names - php

Is it possible to use php to rename files in directory to match the output of a js file created. I have thousands of images downloaded from an API i was using , but switched my app to a new API and had to match up the old imageID with the new imageID. I'd rather batch rename the files instead of having the js file loaded to get the new id names. I have little experience in php and all the tutorials were simple file rename and nothing more complex like this.
img.js
var img_ar = {
"pid_12685":"2578377",
"pid_12757":"2980444",
"pid_12916":"3056906"
}
Current image file names /images
2578377.png
2980444.png
3056906.png
Desired file names after running php script
pid_12685.png (old file name 2578377.png)
pid_12757.png (old file name 2980444.png)
pid_12916.png (old file name 3056906.png)

you can make a php script (not necessary in your web server) and then call it by php your_script.php
in that script you can use scandir to get an array of all the images in your images directory
then you have to loop through that array and use the rename function to rename images
since i don't see a relation between old name number and the new name number
you can create an array
$names = [
'2578377.png' => 'pid_12685.png'
'2980444.png' => 'pid_12757.png'
'3056906.png' => 'pid_12916.png'
];
then, in your loop do rename($imageName, $names[$imageName]);
you can use this script:
either put the script in your images directory, or change the $path variable so the script will use the right directory
change $names to include all your images
<?php
$path = '.';
$files = array_diff(scandir($path), ['.', '..']);
$names = [
'2578377.png' => 'pid_12685.png',
'2980444.png' => 'pid_12757.png',
'3056906.png' => 'pid_12916.png'
];
foreach($files as $file){
if(is_file($file) && isset($names[$file])){
rename($file, $names[$file]);
}
}
call the script by php script_name.php

Related

PHP Delete files in directory if the name is in provided list

I am completely new in PHP and I am trying to achieve simple goal and I need your help please.
I would like to write a script that would take an array of values and delete all the files from the parent folder.
So basically loop in array of file names, and for each name from the array try to find file with same name and if found -> delete it.
So far I achieved to get list of files from the parent folder by using $files = scandir('../');
I cannot find a syntax that would take a list of names and then loop through the $files and deletes everything that match the name from the provided list.
Example:
array ('1.jpg', '2.jpg') -> List of file names that I need to delete
$files = scandir('../') -> List of actual files in the parent folder
action -> 'deleted file '1.jpg' and '2.jpg' from the parent folder
I hope that it is understandable what I am trying to achieve :D
Thanks a lot!
I was able to delete one file in the parent folder using "hardcoded" name
<?php
$path = '../config.php';
if (!unlink($path)) {
echo 'File not deleted';
} else {
echo 'File' . $path . ' deleted successfuly!';
}
I also tried to get a list of all files in the parent folder using
<?php
$files = scandir('../');
var_dump($files);

Move bulk files from one folder to the folders associated with the files

I got a csv file, that looks like the following image :
Now there are pdf files in a dir(resources/pdfFiles) that match the Number columns (1,2,3 etc) of that csv file. Now what I am trying to do is, when a button is triggered, all those pdf files will be moved to another folder. But I have a twist here,The Name column of that csv file are the names of subfolders where the associate numbered files will be stored. For example,pdf files from 1-8 matches with Akaar IT Ltd, therefore these files (1-8) will be moved to the folder called Akaar It Ltd. If there is no such folder exists, then it will be generated automatically.
My code so far are :
$path = resource_path('pdfFiles');
$files = \File::files($path);
foreach($files as $key => $file) {
$filename = basename($files[$key]);
$destinationFilePath = public_path('upload/'.$filename );
rename($files[$key], $destinationFilePath);
}
dd("probably done");
What it's doing is moving all files from one folder to another.

How do I call extract_to_pathname function on a user uploaded zip file?

I have an instance of an activity and when I want to view it I want to extract the associated zip file to be extracted and set the index.html file inside to be the starting page inside view.php.
I found out that the filepath I passed in the extract function doesn't exist, but I can access its fields in the database.
How do I properly pass in the filepath parameter?
Edit:
$fp = get_file_packer('application/zip');
$fileinfo = array(
'component' => 'mod_game',
'filearea' => 'content',
'itemid' => 0,
'contextid' => 472,
'filepath' => '/',
'filename' => 'game.7z');
$myfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
$fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']);
$filepath = '/'.$context->id.'/mod_game/content/'.$game->revision.$myfile->get_filepath().$myfile->get_filename();
$files = $fp->extract_to_pathname($filepath, $CFG->dirroot.'/mod/game/games'.$filepath.'_extracted');
I can see a number of issues here.
Firstly, the file ending (.7z) suggests that this is not a Zip file, but 7Zip file, which Moodle does not (as far as I am aware) support the unzipping of.
The next problem is that you don't appear to have created the folder into which you want to extract the files - you need to create the destination folder, before you try to extract files into it.
Finally, you appear to be trying to pass the (partial?) URL of the file to unzip, rather than either the path to it on the server (NOT recommended in this case) or the stored_file instance itself (strongly recommended).
Unless you need these long term, I would suggest a better solution would look like this:
// Make a temporary folder that will be automatically deleted at the end of the request.
$dest = make_request_directory();
// Extract the stored_file instance into this destination.
$files = $fp->extract_to_pathname($myfile, $dest);

Php keyword search in file name in a directory and download

I have a list of files in a directory of some local path with names like APX-904-118000945-NMR-ETC with different extensions. For every file name a code exists, in this filename 118000945, using which i want to search and download that file in php.
I am able to pass the code i.e., 118000945 but unable to search for it and download with some piece of code got from web.
Could you help me out in writing a php script for this?
Consider using the symfony finder component
$idToFind = '118000945';
$finder = new Finder();
$finder->files()
->in('/path/to/dir')
->name(sprintf('*%s*', $idToFind));
foreach ($finder as $file) {
$absoluteFilePath = $file->getRealPath();
$fileNameWithExtension = $file->getRelativePathname();
// ...
}

Select file(s) in a directory based upon complex filename

I have audio files in var/
This is the file name
2-3109999999-3246758493-1271129518-1271129505.6.wav
Format
2=campaign id
3109999999=caller id
3246758493=number called
1271129518=timestamp call ended
1271129505=timestamp call started
6=call id
If I were to pass just the number called which was 3246758493, how can I find all the files without defining all the other variables(such as timestamp, etc) and just the files that have that number in the filename?
You would need to loop though the folder: http://php.net/manual/en/function.readdir.php
Then for each of the files in the folder, try and match it to the file that was requested using regex I guess?
http://www.txt2re.com/index-php.php3?s=2-3109999999-3246758493-1271129518-1271129505.6.wav&8
You could also use a DirectoryIterator to scan the folder and a RegexIterator to filter the files based on a pattern.
$id = '3246758493';
$files = new RegexIterator(new DirectoryIterator('var/'),
"#^\d-\d{10}-$id-\d{10}-\d{10}\.\d\.wav$#D");
foreach ($files as $fileinfo) {
echo $fileinfo . PHP_EOL;
}

Categories