简体   繁体   中英

PHP - Checking for Uploaded Image

I'm relatively new to PHP and need some help checking to see 1. If an image has been uploaded for submission and complete one set of submission ELSE IF an image has not been uploaded, submit a different set of sql information.

I've previously tried isset(), is_uploaded_file(), and file_exists(), and cannot seem to get anything to send.

HTML FORM

           <form method="POST" action="php/editInv.php" enctype="multipart/form-data" id="editInv">
           <table>
              <tbody>
              <?php
                 $productId = $_GET['productId'];

                 require ('php/dbcon.php');

                 $con=mysqli_connect(HOST,USER,PASS,DB);

                 $sqlId = "SELECT * FROM products WHERE productId='".$productId."'";

                 $sqlIdResult = mysqli_query($con,$sqlId);

                 while($rowId=mysqli_fetch_array($sqlIdResult)) {
              ?>
                 <tr>
                    <td>
                       <label for="productName">Product Name: </label>
                    </td>
                    <td>
                       <input name="productName" id="productName" type="text" value="<?php echo $rowId['productName']; ?>"/>
                       <input name="prodId" id="prodId" type="hidden" value="<?php echo $rowId['productId']; ?>" />
                    </td>
                    <td>
                       <label for="productDesc">Product Description: </label>
                    </td>
                    <td rowspan="4">
                       <textarea name="productDesc" id="productDesc" cols="55" rows="10"><?php echo $rowId['productDesc']; ?></textarea>
                    </td>
                 </tr>
                 <tr>
                    <td>
                       <label for="gender">Gender: </label>
                    </td>
                    <td>
                       <select name="gender" id="gender">
                          <option id="1" value="1">Male</option>
                          <option id="2" value="2">Female</option>
                          <option id="3" value="3">Unisex</option>
                       </select>
                       <input type="hidden" value="<?php echo $rowId['genderId']; ?>" id="genderHid"/>
                       <script>
                          var gender=$('#genderHid').val();
                          var selected=$('#gender').find('#'+gender);
                          $(selected).attr('selected','selected');
                       </script>
                    </td>
                 </tr>
                 <tr>
                    <td>
                       <label for="inventory">Inventory: </label>
                    </td>
                    <td>
                       <input type="number" name="inventory" id="inventory" value="<?php echo $rowId['inventory']; ?>"/>
                    </td>
                 </tr>
                 <tr>
                    <td>
                       <label for="price">Price: </label>
                    </td>
                    <td>
                       $<input type="text" name="price" id="price" value="<?php echo $rowId['price']; ?>" />
                    </td>
                 </tr>
                 <tr>
                    <td>
                       <label for="productImage">Upload Image: </label>
                    </td>
                    <td>
                       <input type="file" name="productImage" id="productImage" />
                    </td>
                    <td colspan="2">
                       <div id="progress" style="width:100%;">
                          <div id="bar" style="height:50px;background-color:blue;width:0%;">
                          </div>
                          <p id="percent"></p>
                       </div>
                    </td>
                 </tr>
                 <tr>
                    <td colspan="2" rowspan="2">
                       <img id="prevImage" style="" src="<?php echo $rowId['productImage']; ?>" />
                    </td>
                    <td id="response">

                    </td>
                    <td>
                       <button type="submit" id="editInv">Edit Item</button>
                    </td>
                 </tr>
                 <tr>
                 </tr>
              <?php
              };
              ?>
              </tbody>
           </table>
           </form>

AJAX

  var options = {
  beforeSubmit: function() {
     // pre submit callback
     $("#progress").show();
     $("#percent").html("0%");
  },
  data: {
     productName : $('#productName').val(),
     productDesc : $('#productDesc').val(),
     inventory : $('#inventory').val(),
     price : $('#price').val(),
     gender : $('#gender').val(),
     image : $('#prevImage').attr('src'),
     prodId : $('#prodId').val()
  },
  uploadProgress: function(event, position, total, percentComplete) {
     //during submission
     $("#bar").width(percentComplete+'%');
     $("#percent").html(percentComplete+'%');
  },
  success: function(msg) {
     //post submit call back
     $(".bar").css("width","100%");
     $(".percent").html('100%');
     $("#response").html(response.responseText);
  },
  complete: function(response) {
     if(response.responseText=="Invalid File"){
     } else {
        $("#response").html(response.responseText);
        //$("#addNew")[0].reset();
        //$("#prevImage").attr('src','').hide();
        $(".bar").css("width","0%");
        $(".percent").html('0%');
     }

  },
  error: function(response) {
     alert(response.responseText);
  }

};

$("#editInv").ajaxForm(options);

PHP

//If a file has been uploaded
if (!empty($_FILES["productImage"]["name"])) {

 $target_dir = $_SERVER['DOCUMENT_ROOT'] . "/images/inventory/";
 $target_file = $target_dir . basename($_FILES["productImage"]["name"]);
 $fileName = str_replace(' ', '', $productName);
 $target_file_insert = "/images/inventory/" . $fileName . ".jpg";
 $targetFileUpload = $target_dir . $fileName . ".jpg";


 $sql1 = "UPDATE products SET productName='".$productName."', productDesc='".$productDesc."', inventory='".$inventory."', price='".$price."', genderId='".$gender."', productImage='".$targetFileUpload."' WHERE productId='".$prodId."'";

 mysqli_query($con,$sql1);

 $uploadOk = 1;
 $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
 // Check if image file is a actual image or fake image
 if(isset($_POST["submit"])) {
     $check = getimagesize($_FILES["productImage"]["tmp_name"]);
     if($check !== false) {
         echo "File is an image - " . $check["mime"] . ".";
         $uploadOk = 1;
     } else {
         echo "File is not an image.";
         $uploadOk = 0;
     }
 }
 // Allow certain file formats
 if($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "JPG" && $imageFileType != "JPEG") {
     echo "Sorry, only JPG, and JPEG files are allowed.";
     $uploadOk = 0;
 }
 // Check if $uploadOk is set to 0 by an error
 if ($uploadOk == 0) {
     echo "Sorry, your file was not uploaded.";
 // if everything is ok, try to upload file
 } else {
     if (move_uploaded_file($_FILES["productImage"]["tmp_name"], $targetFileUpload)) {
         mysqli_close($con);
     } else {
         echo "Sorry, there was an error uploading your file.";
     }
 }
} else
//If a file has not been uploaded
/*if (empty($_FILES["productImage"]["name"])) */{
  $sql2="UPDATE products SET productName='".$productName."', productDesc='".$productDesc."', inventory='".$inventory."', price='".$price."', genderId='".$gender."', productImage='".$image."' WHERE productId='".$prodId."'";

  mysqli_query($con,$sql2);
}

The path you need to check is $targetFileUpload not $upload .

Once uploaded check:

if (!file_exists($targetFileUpload)){...}

Ok, it was actually being caused by two different issues, one in the PHP and one in the order in which the variables were called in the JavaScript. I had to call everything except for the generated image using jQuery at the top of the page as global variables, then put the jQuery AJAX at the bottom of the page with the form action call.

Apparently, using the jQuery to call the values of the fields at the bottom of the page caused them to send the information that the page populated with from the back end, while placing them at the top of the page causes them to relay the changed input data to the AJAX call.

Any explinations why this worked this way?

  <script>
      var productName = $('#productName').val();
      var productDesc = $('#productDesc').val();
      var inventory = $('#inventory').val();
      var price = $('#price').val();
      var gender = $('#gender').val();
      var prodId = $('#prodId').val();
  </script>

//All your HTML Content

<script>
  var options = {
  beforeSubmit: function() {
     // pre submit callback
     $("#progress").show();
     $("#percent").html("0%");
  },
  data: {
     productName : productName,
     productDesc : productDesc,
     inventory : inventory,
     price : price,
     gender : gender,
     image : $('#prevImage').attr('src'),
     prodId : prodId
  },
  uploadProgress: function(event, position, total, percentComplete) {
     //during submission
     $("#bar").width(percentComplete+'%');
     $("#percent").html(percentComplete+'%');
  },
  success: function(msg) {
     //post submit call back
     $(".bar").css("width","100%");
     $(".percent").html('100%');
     $("#response").html(response.responseText);
  },
  complete: function(response) {
     if(response.responseText=="Invalid File"){
     } else {
        $("#response").html(response.responseText);
        //$("#addNew")[0].reset();
        //$("#prevImage").attr('src','').hide();
        $(".bar").css("width","0%");
        $(".percent").html('0%');
     }

  },
  error: function(response) {
     alert(response.responseText);
  }

};


$("#editInv").ajaxForm(options);
  </script>

PHP if statement statement essentially looks like this:

if (!empty($_FILES["productImage"]["name"])) {
} else
//If a file has not been uploaded
if (empty($_FILES["productImage"]["name"])) {
}

Thank you @fred-ii- for the error catcher.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM