-2

i have been trying to rename all the files (images) in a folder on my website but it does not work. the files are not renamed.

i have an input field for 'name' i want to use that name, add a uniqid and rename all the files. here's the code that i am using:

<?php
if(isset($_POST['submit2'])){
$name = $_POST['name'];
$directory = glob("../basic_images/*.*");
{
if ($file != "." && $file != "..") {

    $newName = uniqid().$name;

    rename($directory.$file, $directory.$newName);
}}}
?>

besides, do i really need to _Post the $name variable?

P.S. i want to rename all the files and then copy them to another folder.

azula
  • 56
  • 12
  • 1
    'Can't seem to get it to work' is not a good problem description. Please elaborate on the errors or issues you are encountering. – Thernys May 05 '16 at 19:15
  • 2
    You don't define `$file`. – Digital Chris May 05 '16 at 19:16
  • 1
    http://php.net/manual/en/function.glob.php – Digital Chris May 05 '16 at 19:17
  • `Several of the examples use a notation "*.*" when just plain "*" does the same thing. The "*.*" notation is misleading as it implies foo.ext will not be found with "*" because the "." is not present.` - Gotten from http://php.net/manual/en/function.glob.php – Jack Hales May 05 '16 at 19:23
  • the problem was that the files didn't get renamed - nothing happened - no error message. – azula May 10 '16 at 12:04

2 Answers2

0

You don't need to POST name

glob is return you every files in folder with path // example /basic_images/test.jpg

then you just do foreach to loop over files, and update its name.

$path = "../basic_images/";
$directory = glob($path,"*.*");
foreach($directory as $file){
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    $newName = uniqid().$ext;
    rename($file, $path.$newName);
} 

read more about glob : http://php.net/manual/en/function.glob.php

Natsathorn
  • 1,530
  • 1
  • 12
  • 26
0

so, i finally solved the problem. now, instead of renaming the original files and then copying them to another folder, i just create new copies of the files with new names.

This is the code final code that works for me:

if(isset($_POST['submit'])){

$path = "../posts_images/";
$files = glob("../basic_images/*.*");
foreach($files as $file){
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    $name = $_POST['new_name'];
    $pic = uniqid().$name;
    $newName = $pic.'.'.$ext;
    copy($file, $path.$newName);

}}

it is important to use $pic.'.'.$ext because without it the new files don't have any extension.

azula
  • 56
  • 12