0

when i upload image with same name it replace my precending imagage. I want to give him number (increment that number) 1_name.png, 2_name.png. This is my code:

if(isset($_POST['submit_im'])) {
    $name = $_FILES['file']['name'];
    $tmp_name = $_FILES['file']['tmp_name'];
    $location = 'uploads/';
    $target = 'uploads/'.$name;

    if(file_exists('uploads/'.$name)) {
        $i = 1;
        while(file_exists('uploads/'.$i."_".$name)) {
            $i++;
        }
        $name = $i."_".$name;
    }

    if(move_uploaded_file($tmp_name,$location.$name)) {
        $title = $_POST['title'];
        $query = "INSERT INTO obrazky(img,title) VALUES ('".$target."','$title')";
        $result = mysqli_query($connection, $query);
    } else {

Thanks for help :)

Forlis
  • 177
  • 2
  • 3
  • 12

1 Answers1

2

You can do it far simpler, just count the amount of files you have in your directory and increase it by 1.

$cntFiles = count(array_diff( scandir("/uploads"), array(".", "..") ));
$cntFiles++; // Increase by 1 for the next number
$name = $cntFiles."_".$name;

We do the array_diff() to remove the . and .. entries that are coming from the file-system, but don't represent files in that directory.

Also, you have some issues in your code

$target = 'uploads/'.$name;

if(file_exists('uploads/'.$name)) {
    $i = 1;
    while(file_exists('uploads/'.$i."_".$name)) {/*...*/}

First, you're checking against 2 different filenames. The name is unlikely to be used at this point, because you're checking for the name that the file was uploaded with.

Second, you've defined a variable with the filename, but you're not using it.

$target = 'uploads/'.$name;
if(file_exists($target)) {/*...*/}

Also, your code is vulnerable to SQL Injection, but that's covered in the linked question.

Community
  • 1
  • 1
KhorneHoly
  • 4,666
  • 6
  • 43
  • 75
  • @Forlis If this answer has helped you, it would be good if you accept it with the green checkmark underneath the voting icons. This marks the question as answered. – KhorneHoly Feb 07 '17 at 18:36