Skip to content
Advertisement

After changing name of a file it goes parent directory

I’m writing a PHP code that takes names from input.txt file and with those names it changes the names of files in the image folder.

My code is:

<?php
$array = explode(".png", file_get_contents('input.txt'));

$directory='C:wamp64wwwReplace image names with inputimages';
$extension = '.png';
$a=0;
$newName='';

$dir = "images/*";

foreach(glob($dir) as $file)
{
    if(!is_dir($file)) {
        echo basename($file)."n";
        $newName=$array[$a].".png";
        rename($file, $newName);
        $a++;
    }
}    
?>

It works but at last, files in the ‘image’ folder go C:wamp64wwwReplace image names with input directory. (Parent directory)

Any idea why this happens?

Advertisement

Answer

To make it more clear. Here is what your code is doing:

$dir = "images/*";

foreach(glob($dir) as $file) {
// at this point $file === "images/filename"
    if(!is_dir($file)) {
        echo basename($file)."n";
        $newName=$array[$a].".png";
// You set the $newName to newname.png
        rename($file, $newName);
// you replace "images/filename" with "newname.png"
        $a++;
    }
}

effectively you’ve written a move and rename function. For simplicity you can just do:

$newName="images/".$array[$a].".png"
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement