2

I've been working with image uploading and am wondering why this isn't working correctly? It doesn't move/upload the file with the new name if it already exists.

if(isset($_REQUEST['submit'])){
     $filename=  $_FILES["imgfile"]["name"];
        if ((($_FILES["imgfile"]["type"] == "image/gif")|| ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png")  || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 20000000)){
    $loc = "userpics/$filename";
    if(file_exists($loc)){
        $increment = 0;
        list($name, $ext) = explode('.', $loc);
        while(file_exists($loc)) {
            $increment++;
            $loc = $name. $increment . '.' . $ext;
            $filename = $name. $increment . '.' . $ext;
        }
      move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$loc");

    }
    else{
      move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$filename");

    }
     }
     else{
    echo "invalid file.";
     }
}
user3753779
  • 23
  • 1
  • 1
  • 4

2 Answers2

5

You've included the folder path in $loc, then you attempt to move a file to userpics/$loc, which is probably incorrect. See the comments:

$filename = "example.jpg";
$loc = "userpics/$filename";
if(file_exists($loc)){
    $increment = 0;
    list($name, $ext) = explode('.', $loc);
    while(file_exists($loc)) {
        $increment++;
        // $loc is now "userpics/example1.jpg"
        $loc = $name. $increment . '.' . $ext;
        $filename = $name. $increment . '.' . $ext;
    }

    // Now you're trying to move the uploaded file to "userpics/$loc"
    //   which expands to "userpics/userpics/example1.jpg"
    move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$loc");
} else {
    // ...

As a general debugging tip, always check a function's return value to see if it was successful. Secondly, display the function's input values if it's failing. It will make debugging things a lot easier.

Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
0

Try this:

$fullpath = 'images/1086_002.jpg';
$additional = '1';

while (file_exists($fullpath)) {
    $info = pathinfo($fullpath);
    $fullpath = $info['dirname'] . '/'
              . $info['filename'] . $additional
              . '.' . $info['extension'];
}

Thanks to here:Clickie!!

Community
  • 1
  • 1
LisaW
  • 171
  • 2
  • 3
  • 11