Home > Mobile >  Php rename files using js file that contains names
Php rename files using js file that contains names

Time:10-23

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)

CodePudding user response:

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:

  1. either put the script in your images directory, or change the $path variable so the script will use the right directory

  2. 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]);
        }
    }
    
  3. call the script by php script_name.php

  •  Tags:  
  • php
  • Related