PHP $_FILES same image name

1.7k Views Asked by At

I am trying to upload multiple images to php server, But for some reason it is using first image name for all the uploaded images, saving to same image name. I want it to save to their filename in the source folder. Like Banner1.jpg,Banner2.jpg and Banner3.jpg should be saved. But it is saving first image thrice.

$filesCount = count($_FILES['photos']['name']);
            $success = 0;
            for($i = 0; $i < $filesCount; $i++)
            {
                $uploadedfile = $_FILES['photos']['tmp_name'][$i];

                if($uploadedfile)
                {
                    $filename  = stripcslashes($_FILES['photos']['name'][$i]);
                    $extension = $this->getExtension($filename);
                    $extension = strtolower($extension);

                    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
                    {       
                        $change='<div class="msgdiv">Unknown Image extension </div>';
                    }
                    else
                    {
                        $size = filesize($_FILES['photos']['tmp_name'][$i]);
                    }
                    if($size > MAX_SIZE*1024)
                    {
                        $change='<div class="msgdiv">You have exceeded the size limit!</div> ';
                    }
                    if($extension=="jpg" || $extension=="jpeg" )
                    {
                        $uploadedfile = $_FILES['photos']['tmp_name'][$i];
                        $src = imagecreatefromjpeg($uploadedfile);
                    }
                    else if($extension=="png")
                    {
                        $uploadedfile = $_FILES['photos']['tmp_name'][$i];
                        $src = imagecreatefrompng($uploadedfile);
                    }
                    else 
                    {
                        $src = imagecreatefromgif($uploadedfile);
                    }

                    list($width,$height)=getimagesize($uploadedfile);   
                    $newwidth=1024;
                    $newheight=($height/$width)*$newwidth;
                    $tmp=imagecreatetruecolor($newwidth,$newheight);

                    $newwidth1=300;
                    $newheight1=($height/$width)*$newwidth1;
                    $tmp1=imagecreatetruecolor($newwidth1,$newheight1);

                    imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
                    imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);

                    $filenameee = "server/php/rental/". $_FILES['photos']['name'][$i];
                    $filenameee1 = "server/php/rental/small/". $_FILES['photos']['name'][$i];

                    imagejpeg($tmp,$filenameee,100);
                    imagejpeg($tmp1,$filenameee1,100);
                    imagedestroy($src);
                    imagedestroy($tmp);
                    imagedestroy($tmp1);
                    if(mysql_query("INSERT INTO fc_rental_photos(product_image,product_id) VALUES('$filename','$prd_id')"))
                    {
                        $success++;
                    }
                }

Here is the input field i am using to upload images.

<form id="imageform" method="post" enctype="multipart/form-data" action="/path-to-controller-method/">
<input type="file" name="photos[]" id="photoimg" multiple onchange="imageval();">
</form>

IMageVal

function imageval(){   /*Image size validation*/

      var fi = document.getElementById('photoimg');

       if (fi.files.length > 0) {      // FIRST CHECK IF ANY FILE IS SELECTED.

             for (var i = 0; i <= fi.files.length - 1; i++) {
                 var fileName, fileExtension, fileSize, fileType, dateModified;

                 fileName = fi.files.item(i).name;
                 fileExtension = fileName.replace(/^.*\./, '');
                 if (fileExtension == 'png' || fileExtension == 'jpg' || fileExtension == 'jpeg') {

                    var reader = new FileReader();

                    //Read the contents of Image File.

                    reader.readAsDataURL(fi.files.item(i));

                    reader.onload = function (e) {

                        //Initiate the JavaScript Image object.

                        var image = new Image();

                        //Set the Base64 string return from FileReader as source.

                        image.src = e.target.result;

                        //Validate the File Height and Width.

                        image.onload = function () {

                        var height = this.height;

                        var width = this.width;



                        if (width < 1450 || height < 500) {

                        alert("Image Height and Width should be Above 1450 * 500 px.");

                        return false;

                        }

                        <?php if($aws == 'Yes') echo "uploadImage_aws();";else echo "uploadImage();";?>

                    };
                }
             }
             else
             {
                 alert("Photo only allows file types of PNG, JPG, JPEG. ");
             }

       }


    }
}   

UploadImage

function uploadImage()

{

    $("#imageform").ajaxForm({target: '#preview', 

        beforeSubmit:function(){

            $("#imageloadstatus").show();

            $("#imageloadbutton").hide();

        }, 

        success:function(){

            $("#imageloadstatus").hide();

            $("#imageloadbutton").show();

        },

        error:function(){ 

            $("#imageloadstatus").hide();

            $("#imageloadbutton").show();

        }

    }).submit();

}
1

There are 1 best solutions below

5
On

You have to check if the data already exists, and if not to rename it.

if(file_exists($new_path)) {
$id = 1;
do {
    $new_path = $upload_folder.$filename.'_'.$id.'.'.$extension;
    $id++;
} while(file_exists($new_path));

}

For example

$new_path = $upload_folder.$filename.'.'.$extension;