Uploading multiple images for one product

Discussion in 'PHP' started by Mayordomo, Mar 12, 2018.

  1. #1
    Hi folks,
    I have downloaded a script for listing real estate property. Only the last photo to upload shows up. Can anybody look at the code and see if some wrong. Thank you all.

    <?php
    
    $mess_err = '';
    if($_SERVER['REQUEST_METHOD']=="POST")
    {
        if(empty($_POST['txtName'])){
            $mess_err .="+ ".$messhousename."<br />";
            }
        else if(strlen($_POST['txtName'])<6){
            $mess_err .= "+ ".$messlenHN."<br />";
            }
            else $mess_err .= '';
          
        if(intval($_POST['selectTinhTP'])==0){
            $mess_err .= "+ ".$messcity."<br/>";
            }
        else if(intval($_POST['selectDistrict'])==0){
            $mess_err .= "+ ".$messdistrict."<br/>";
            }
          
        if(empty($_POST['txtAddress'])){
            $mess_err .= "+ ".$messaddress."<br/>";
            }
        else if(strlen($_POST['txtAddress'])<6){
            $mess_err .= "+".$messlenaddress."<br/>";
            }
      
      
        if(($_POST['txtLivingsize']=="")){
            $mess_err .= "+ ".$messlivingsize."<br/>";
            }
        if(empty($_POST['captcha'])){
            $mess_err .= "+ ".$messcaptcha."<br>";
            }
        else if($_POST['captcha'] != $_SESSION["security_code"]){
            $mess_err .= "+ ".$messincorrectcaptcha;
            }
        $ten_hinh=$_FILES["imageFile"]['name'];  
        $imgtype=$_FILES['imageFile']['type'];
        $imgsize=$_FILES['imageFile']['size'];  
        if($ten_hinh!=""){
            if ( (($imgtype == "image/gif")|| ($imgtype == "image/jpeg")|| ($imgtype == "image/jpg")|| ($imgtype == "image/pjpeg")|| ($imgtype == "image/png")))
            {
              
                if ($_FILES["imageFile"]["error"] > 0)
                    $mess_err .= "+ ".$imageinvalid."<br>";
                else
                {              
                    if($imgsize>1400000) $mess_err .="+ ".$sizeimage."<br />";
                  
                }
            }
            else $mess_err .= "+ ".$imageinvalid."<br />";
        }
    }
    if(!isset($mess_err))$mess_err=" ";
    if(!isset($mess_success)) $mess_success=" ";
    if(empty($mess_err)&& isset($_POST['sbAddHouse']))
        {
                Connect_Database();
                include('SimpleImage.php');
                if(!isset($_POST['chkIncludeTax']))$_POST['chkIncludeTax'] =0;
                if(!isset($_POST['chkCooling']))$_POST['chkCooling'] =0;
                if(!isset($_POST['chkLaundry']))$_POST['chkLaundry'] =0;
                if(!isset($_POST['chkSwimming']))$_POST['chkSwimming'] =0;
                if(!isset($_POST['chkGarden']))$_POST['chkGarden'] =0;
                if(!isset($_POST['chkYard']))$_POST['chkYard'] =0;
                if(!isset($_POST['chkHeating']))$_POST['chkHeating'] =0;
              
                $noi_dung1=strip_tags($_POST['txtAmenity']);
                $noi_dung1=str_replace("<","&lt;",$noi_dung1);
                $noi_dung1=str_replace(">","&gt;",$noi_dung1);
                $noi_dung1=str_replace("'","&apos;",$noi_dung1);
                $noi_dung1=str_replace('"',"&quot;",$noi_dung1);          
                $noi_dung1=str_replace('<pre>',"",$noi_dung1);
                $noi_dung1=str_replace('</pre>',"",$noi_dung1);
                $noi_dung1=nl2br($noi_dung1);
                $Amenity=$noi_dung1;
              
                $noi_dung=strip_tags($_POST['txtDescription']);
                $noi_dung=str_replace("<","&lt;",$noi_dung);
                $noi_dung=str_replace(">","&gt;",$noi_dung);
                $noi_dung=str_replace("'","&apos;",$noi_dung);
                $noi_dung=str_replace('"',"&quot;",$noi_dung);          
                $noi_dung=str_replace('<pre>',"",$noi_dung);
                $noi_dung=str_replace('</pre>',"",$noi_dung);
                $noi_dung=nl2br($noi_dung);
                $Description=$noi_dung;
                $now1=date("Y-m-d",time()+(14*60*60));
                $query = "insert into houses(city_id, district_id, category_id, user_id, need_id, legal_id, direction_id, name, address, yearbuilt, description, created, lotsize, livingsize, price, includetax, mls, amentities, stories, floorcoverings, rooftype, bathroom, diningroom, bedroom, kitchen, livingroom, miscrooms, heating, cooling, water, sewer, laundry, parking, swimmingpool, garden, yardgrounds, handicapfeatures, status, views, contactname, contactemail, contactphone, contactmobile,latitude,longitude,fulladdress,unit) values(".intval($_POST['selectTinhTP']).", ".intval($_POST['selectDistrict']).",".intval($_POST['selectCate']).",".intval(0).", ".$_POST['selectNeed'].", ".$_POST['selectLegal'].", ".$_POST['selectDirection'].", '".mysql_real_escape_string($_POST['txtName'])."', '".mysql_real_escape_string($_POST['txtAddress'])."', '".mysql_real_escape_string($_POST['txtYearBuilt'])."', '".$Description."','".$now1."', ".intval($_POST['txtLotsize']).", ".$_POST['txtLivingsize'].", ".floatval($_POST['txtnewprice']).", ".$_POST['chkIncludeTax'].", '".mysql_real_escape_string($_POST['txtMLS'])."', '".$Amenity."', ".intval($_POST['txtNumBlock']).", '".mysql_real_escape_string($_POST['txtFloorCovering'])."', '".mysql_real_escape_string($_POST['txtRoofType'])."', ".intval($_POST['txtBathRoom']).", ".intval($_POST['txtDiningRoom']).", ".intval($_POST['txtBedRoom']).", ".intval($_POST['txtKitchen']).", ".intval($_POST['txtLivingRoom']).", '".intval($_POST['txtMiscRoom'])."','".intval($_POST['chkHeating'])."', ".intval($_POST['chkCooling']).", 0, 0, ".intval($_POST['chkLaundry']).", '".intval($_POST['txtParking'])."', ".intval($_POST['chkSwimming']).", ".intval($_POST['chkGarden']).", ".intval($_POST['chkYard']).", '', 0, 0, '".mysql_real_escape_string($_POST['fullname'])."', '".mysql_real_escape_string($_POST['txtemail'])."', '".mysql_real_escape_string($_POST['txtphone'])."', '".mysql_real_escape_string($_POST['txtmobile'])."','".mysql_real_escape_string($_POST['lat'])."','".mysql_real_escape_string($_POST['lng'])."','".mysql_real_escape_string($_POST['newaddress'])."','".$_POST['selectTime']."')";
                            if(QuerySQL($query)) {$mess_err="+ ".$postnewssuc;}
                            else {echo "Error insert";$mess_success="";}
                          
                            if($ten_hinh!=""){
                                $newimgtype=substr($imgtype,6);
                                $length = 8;                  
                                $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                                $rndstr = '';  
                                for ($p = 0; $p < $length; $p++) {
                                    $rndstr .= $characters[mt_rand(0, strlen($characters))];
                                }  
                              
                                $newImagename=md5(date('m/d/Y h:i:s').$rndstr).".".$newimgtype;
                              
                                $newimage = new SimpleImage();
                                $newimage->load($_FILES['imageFile']['tmp_name']);
                                $newimage->resize(660,400);
                                $newimage->save("uploads/" .$newImagename);
                                $sql ="INSERT INTO `imgs` (`house_id` ,`name`,`mainimg`,status)    VALUES (".mysql_insert_id().",'$newImagename',1,0)";          
                                            $rs = QuerySQL($sql);
                            }
                Close_Connect();
            }
    ?>
    
    <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" name="formAddHouse"onsubmit="return checkFormAddHouse();" enctype="multipart/form-data">
    <input type="file" name="imageFile" id="imageFile" />
    <input type="file" name="imageFile" id="imageFile" />
    <input type="file" name="imageFile" id="imageFile" />
    <input type="submit" value="<?php echo strtoupper($addhouse);?>" id="sbAddHouse" name="sbAddHouse" style="width:100px;" onclick="window.location.href='#here';" >
    </form>
    PHP:

     
    Last edited by a moderator: Mar 12, 2018
    Mayordomo, Mar 12, 2018 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,807
    Likes Received:
    4,534
    Best Answers:
    123
    Trophy Points:
    665
    #2
    The name of the field that captures the image isn't an array, and it's all the same, so you need to change it so that it matches one of these
    <input type="file" name="imageFile[]" id="imageFile" />
    <input type="file" name="imageFile[]" id="imageFile" />
    <input type="file" name="imageFile[]" id="imageFile" />
    PHP:
    or
    <input type="file" name="imageFile1" id="imageFile" />
    <input type="file" name="imageFile2" id="imageFile" />
    <input type="file" name="imageFile3" id="imageFile" />
    PHP:
    and then you need a foreach at line 37 that ends at about line 111
     
    sarahk, Mar 12, 2018 IP
  3. Mayordomo

    Mayordomo Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #3
    Thank you very much. I have tried using different names for the input element like you suggested but no image is uploaded at all. Could you please help with how the foreach would look like in this particular case.
     
    Mayordomo, Mar 13, 2018 IP
  4. sarahk

    sarahk iTamer Staff

    Messages:
    28,807
    Likes Received:
    4,534
    Best Answers:
    123
    Trophy Points:
    665
    #4
    untested but this should help. Common code put into a function, there's lots more to do to make this "elegant" and some of it I couldn't follow but you should learn a lot by comparing my code to yours.

    <?php
    function saveUploadedFile($counter, $file, $house_id){
    
        $mess_err = [];
    
        $validTypes = ["image/gif", "image/jpeg", "image/jpg", "image/pjpeg", "image/png"];
        $ten_hinh=$file['name']; 
        $imgtype=$file['type'];
        $imgsize=$file['size']; 
    
        if(empty($ten_hinh)){
            return; 
        }
        if ( !in_array($imgtype, $validTypes)) {
    
            if ($_FILES["imageFile"]["error"] > 0){
                $mess_err[] = "+ {$imageinvalid}";
            }
            elseif($imgsize>1400000) {
                $mess_err[] ="+ {$sizeimage}";
            }
            else $mess_err[] = "+ {$imageinvalid}";
        }
        else {
            $newimgtype=substr($imgtype,6);
            $newImagename = makeRandomFileName(8, $newimgtype);
    
            $newimage = new SimpleImage();
            $newimage->load($file['tmp_name']);
            $newimage->resize(660,400);
            $newimage->save("uploads/" .$newImagename);
            $mainimg = ($k == 0)?1:0;
            $sql ="INSERT INTO `imgs` (`house_id` ,`name`,`mainimg`, `status`) VALUES ('{$house_id}','{$newImagename}',{$mainimg},0)";         
            $rs = QuerySQL($sql);
        }
    
        return $mess_err;
    }
    
    function makeRandomFileName($length, $fileType){
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rndstr = ''; 
        for ($p = 0; $p < $length; $p++) {
            $rndstr .= $characters[mt_rand(0, strlen($characters))];
        } 
    
        $newImagename=md5(date('m/d/Y h:i:s').$rndstr).".".$fileType;
        return $newImagename;
    
    }
    
    
    ////////////////////////////////////////////
    include('SimpleImage.php');
    
    $mess_err = $mess_success = [];
    
    if($_SERVER['REQUEST_METHOD']=="POST")
    {
        if(empty($_POST['txtName'])){
            $mess_err[] = $messhousename;
        }
        else if(strlen($_POST['txtName'])<6){
            $mess_err[] = $messlenHN;
        }
    
    
        if(intval($_POST['selectTinhTP'])==0){
            $mess_err[] =  $messcity;
        }
        else if(intval($_POST['selectDistrict'])==0){
            $mess_err[] = $messdistrict;
        }
    
        if(empty($_POST['txtAddress'])){
            $mess_err[] = $messaddress;
        }
        else if(strlen($_POST['txtAddress'])<6){
            $mess_err[] = $messlenaddress;
        }
    
    
        if(($_POST['txtLivingsize']=="")){
            $mess_err[] = $messlivingsize;
        }
        if(empty($_POST['captcha'])){
            $mess_err[] = $messcaptcha;
        }
        else if($_POST['captcha'] != $_SESSION["security_code"]){
            $mess_err[] = $messincorrectcaptcha;
        }
    
        if(count($mess_err) == 0 && array_key_exists('sbAddHouse', $_POST){
            Connect_Database();
    
            if(!isset($_POST['chkIncludeTax']))$_POST['chkIncludeTax'] =0;
            if(!isset($_POST['chkCooling']))$_POST['chkCooling'] =0;
            if(!isset($_POST['chkLaundry']))$_POST['chkLaundry'] =0;
            if(!isset($_POST['chkSwimming']))$_POST['chkSwimming'] =0;
            if(!isset($_POST['chkGarden']))$_POST['chkGarden'] =0;
            if(!isset($_POST['chkYard']))$_POST['chkYard'] =0;
            if(!isset($_POST['chkHeating']))$_POST['chkHeating'] =0;
    
            $noi_dung1=strip_tags($_POST['txtAmenity']);
            $noi_dung1=str_replace("<","&lt;",$noi_dung1);
            $noi_dung1=str_replace(">","&gt;",$noi_dung1);
            $noi_dung1=str_replace("'","&apos;",$noi_dung1);
            $noi_dung1=str_replace('"',"&quot;",$noi_dung1);         
            $noi_dung1=str_replace('<pre>',"",$noi_dung1);
            $noi_dung1=str_replace('</pre>',"",$noi_dung1);
            $noi_dung1=nl2br($noi_dung1);
            $Amenity=$noi_dung1;
    
            $noi_dung=strip_tags($_POST['txtDescription']);
            $noi_dung=str_replace("<","&lt;",$noi_dung);
            $noi_dung=str_replace(">","&gt;",$noi_dung);
            $noi_dung=str_replace("'","&apos;",$noi_dung);
            $noi_dung=str_replace('"',"&quot;",$noi_dung);         
            $noi_dung=str_replace('<pre>',"",$noi_dung);
            $noi_dung=str_replace('</pre>',"",$noi_dung);
            $noi_dung=nl2br($noi_dung);
            $Description=$noi_dung;
            $now1=date("Y-m-d",time()+(14*60*60));
            $query = "insert into houses(city_id, district_id, category_id, user_id, need_id, legal_id, direction_id, name, address, yearbuilt, description, created, lotsize, livingsize, price, includetax, mls, amentities, stories, floorcoverings, rooftype, bathroom, diningroom, bedroom, kitchen, livingroom, miscrooms, heating, cooling, water, sewer, laundry, parking, swimmingpool, garden, yardgrounds, handicapfeatures, status, views, contactname, contactemail, contactphone, contactmobile,latitude,longitude,fulladdress,unit) values(".intval($_POST['selectTinhTP']).", ".intval($_POST['selectDistrict']).",".intval($_POST['selectCate']).",".intval(0).", ".$_POST['selectNeed'].", ".$_POST['selectLegal'].", ".$_POST['selectDirection'].", '".mysql_real_escape_string($_POST['txtName'])."', '".mysql_real_escape_string($_POST['txtAddress'])."', '".mysql_real_escape_string($_POST['txtYearBuilt'])."', '".$Description."','".$now1."', ".intval($_POST['txtLotsize']).", ".$_POST['txtLivingsize'].", ".floatval($_POST['txtnewprice']).", ".$_POST['chkIncludeTax'].", '".mysql_real_escape_string($_POST['txtMLS'])."', '".$Amenity."', ".intval($_POST['txtNumBlock']).", '".mysql_real_escape_string($_POST['txtFloorCovering'])."', '".mysql_real_escape_string($_POST['txtRoofType'])."', ".intval($_POST['txtBathRoom']).", ".intval($_POST['txtDiningRoom']).", ".intval($_POST['txtBedRoom']).", ".intval($_POST['txtKitchen']).", ".intval($_POST['txtLivingRoom']).", '".intval($_POST['txtMiscRoom'])."','".intval($_POST['chkHeating'])."', ".intval($_POST['chkCooling']).", 0, 0, ".intval($_POST['chkLaundry']).", '".intval($_POST['txtParking'])."', ".intval($_POST['chkSwimming']).", ".intval($_POST['chkGarden']).", ".intval($_POST['chkYard']).", '', 0, 0, '".mysql_real_escape_string($_POST['fullname'])."', '".mysql_real_escape_string($_POST['txtemail'])."', '".mysql_real_escape_string($_POST['txtphone'])."', '".mysql_real_escape_string($_POST['txtmobile'])."','".mysql_real_escape_string($_POST['lat'])."','".mysql_real_escape_string($_POST['lng'])."','".mysql_real_escape_string($_POST['newaddress'])."','".$_POST['selectTime']."')";
            if(QuerySQL($query)) {
                $mess_err[] = $postnewssuc;
            }
            else {
                echo "Error insert";
            }
    
            $house_id = mysql_insert_id()
    
    
            foreach($_FILES['imageFile' as $k => $file]){
                $mess_err[] = saveUploadedFile($k, $file, $house_id);
            }
    
            Close_Connect();
        }
    
    
    if (count($mess_err)) {
    echo '+ '. implode('<br/>+ ', $mess_err);
    }
        ?>
    
        <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" name="formAddHouse"onsubmit="return checkFormAddHouse();" enctype="multipart/form-data">
        <input type="file" name="imageFile[]" id="imageFile" />
        <input type="file" name="imageFile[]" id="imageFile" />
        <input type="file" name="imageFile[]" id="imageFile" />
        <input type="submit" value="<?php echo strtoupper($addhouse);?>" id="sbAddHouse" name="sbAddHouse" style="width:100px;" onclick="window.location.href='#here';" >
        </form>
    PHP:
     
    sarahk, Mar 13, 2018 IP