Jump to content

Recommended Posts

Hey all :)

So have been working on a file upload script, it was uploading the file but also adding the path name instead of NULL to mysql when no image was to upload, that is now fixed however now it won't upload the actual image to the directory.  I tried undoing the mysql changes but it still won't upload the image to the directory.  Am testing on my own computer using xampp so no file permission issues, plus it was working before.  Any help much appreciated.

Thanks :)

              <?php
              $product_code = mysqli_real_escape_string($conn, $_POST['product_code']);
              $product_name = mysqli_real_escape_string($conn, $_POST['product_name']);
              $category = mysqli_real_escape_string($conn, $_POST['category']);
              $filter = mysqli_real_escape_string($conn, $_POST['filter']);
              $description = mysqli_real_escape_string($conn, $_POST['description']);
              $specification = mysqli_real_escape_string($conn, $_POST['specification']);
              $price = mysqli_real_escape_string($conn, $_POST['price']);

              $target_dir = "../images/products/";

              if (!isset ($_FILES["img1"]["name"])) {
                  $target_file1 = NULL;
              } else {
                  if (!empty($_FILES["img1"]["name"])) {
                      $target_file1 = $target_dir . basename($_FILES["img1"]["name"]);
                  } else {
                      $target_file1 = NULL;
                  }
              }

              if (!isset ($_FILES["img2"]["name"])) {
                  $target_file2 = NULL;
              } else {
                  if (!empty($_FILES["img2"]["name"])) {
                      $target_file2 = $target_dir . basename($_FILES["img2"]["name"]);
                  } else {
                      $target_file2 = NULL;
                  }
              }

              if (!isset ($_FILES["img3"]["name"])) {
                  $target_file3 = NULL;
              } else {
                  if (!empty($_FILES["img3"]["name"])) {
                      $target_file3 = $target_dir . basename($_FILES["img3"]["name"]);
                  } else {
                      $target_file3 = NULL;
                  }
              }

              if (!isset ($_FILES["img4"]["name"])) {
                  $target_file4 = NULL;
              } else {
                  if (!empty($_FILES["img4"]["name"])) {
                      $target_file4 = $target_dir . basename($_FILES["img4"]["name"]);
                  } else {
                      $target_file4 = NULL;
                  }
              }


              $uploadOk = 1;
              $imageFileType1 = strtolower(pathinfo($target_file1,PATHINFO_EXTENSION));
              $imageFileType2= strtolower(pathinfo($target_file2,PATHINFO_EXTENSION));
              $imageFileType3 = strtolower(pathinfo($target_file3,PATHINFO_EXTENSION));
              $imageFileType4 = strtolower(pathinfo($target_file4,PATHINFO_EXTENSION));

              // Check if image file is a actual image or fake image
              if(isset($_POST["submit"])) {
                $check1 = getimagesize($_FILES["img1"]["tmp_name"]);
                $check2 = getimagesize($_FILES["img2"]["tmp_name"]);
                $check3 = getimagesize($_FILES["img3"]["tmp_name"]);
                $check4 = getimagesize($_FILES["img4"]["tmp_name"]);

                if($check1 !== false) {
                  echo "File is an image - " . $check1["mime"] . ".";
                  $uploadOk = 1;
                } else {
                  echo "File is not an image.";
                  $uploadOk = 0;
                }
                if (file_exists($target_file1)) {
                  echo "Sorry, image one already exists.";
                  $uploadOk = 0;
                }
                if($imageFileType1 != "jpg" && $imageFileType1 != "png" && $imageFileType1 != "jpeg"
                && $imageFileType1 != "gif" ) {
                  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img1.";
                  $uploadOk = 0;
                }
                if ($uploadOk == 0) {
                  echo "Sorry, your file was not uploaded.";
                // if everything is ok, try to upload file
                } else {
                  if (move_uploaded_file($_FILES["img1"]["tmp_name"], $target_file1)) {
                    echo "The file ". htmlspecialchars( basename( $_FILES["img1"]["name"])). " has been uploaded.";
                  } else {
                    echo "Sorry, there was an error uploading image one.";
                  }
                    }
                    echo '<br />';


                if($check2 !== false) {
                  echo "File is an image - " . $check2["mime"] . ".";
                  $uploadOk = 1;
                } else {
                  echo "File is not an image.";
                  $uploadOk = 0;
                }
                if (file_exists($target_file2)) {
                  echo "Sorry, image two already exists.";
                  $uploadOk = 0;
                }
                if($imageFileType2 != "jpg" && $imageFileType2 != "png" && $imageFileType2 != "jpeg"
                && $imageFileType2 != "gif" ) {
                  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img2.";
                  $uploadOk = 0;
                }
                if (isset ($target_file2)) {
                    if ($uploadOk == 0) {
                      echo "Sorry, your file was not uploaded.";
                    // if everything is ok, try to upload file
                    } else {
                    if (move_uploaded_file($_FILES["img2"]["tmp_name"], $target_file2)) {
                      echo "The file ". htmlspecialchars( basename( $_FILES["img1"]["name"])). " has been uploaded.";
                    } else {
                      echo "Sorry, there was an error uploading image two.";
                    }
                      }
                    }
                                        echo '<br />';



                if($check3 !== false) {
                  echo "File is an image - " . $check3["mime"] . ".";
                  $uploadOk = 1;
                } else {
                  echo "File is not an image.";
                  $uploadOk = 0;
                }
                if (file_exists($target_file3)) {
                    echo "Sorry, image three already exists.";
                    $uploadOk = 0;
                  }
                  if($imageFileType3 != "jpg" && $imageFileType3 != "png" && $imageFileType3 != "jpeg"
                    && $imageFileType3 != "gif" ) {
                      echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img3.";
                      $uploadOk = 0;
                    }
                    if (isset ($target_file3)) {
                      if ($uploadOk == 0) {
                        echo "Sorry, your file was not uploaded.";
                      // if everything is ok, try to upload file
                      } else {
                      if (move_uploaded_file($_FILES["img3"]["tmp_name"], $target_file3)) {
                        echo "The file ". htmlspecialchars( basename( $_FILES["img3"]["name"])). " has been uploaded.";
                      } else {
                        echo "Sorry, there was an error uploading image three.";
                      }
                        }
                      }
                                          echo '<br />';


                if($check4 !== false) {
                  echo "File is an image - " . $check4["mime"] . ".";
                  $uploadOk = 1;
                } else {
                  echo "File is not an image.";
                  $uploadOk = 0;
                }
                if (file_exists($target_file4)) {
                      echo "Sorry, image four already exists.";
                      $uploadOk = 0;
                    }
                    if($imageFileType4 != "jpg" && $imageFileType4 != "png" && $imageFileType4 != "jpeg"
                      && $imageFileType4 != "gif" ) {
                        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img4.";
                        $uploadOk = 0;
                      }
                      if (isset ($target_file4)) {
                        if ($uploadOk == 0) {
                          echo "Sorry, your file was not uploaded.";
                        // if everything is ok, try to upload file
                        } else {
                        if (move_uploaded_file($_FILES["img4"]["tmp_name"], $target_file4)) {
                          echo "The file ". htmlspecialchars( basename( $_FILES["img4"]["name"])). " has been uploaded.";
                        } else {
                          echo "Sorry, there was an error uploading image four.";
                        }
                      }
              }
}

  echo '<br />';

$image1 = basename($target_file1);
$image2 = basename($target_file2);
$image3 = basename($target_file3);
$image4 = basename($target_file4);


// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO products (product_code, product_name, category, filter, description, specification, img1, img2, img3, img4, price) VALUES('$product_code', '$product_name', '$category', '$filter', '$description', '$specification', '$image1', '$image2', '$image3', '$image4', '$price')";

if (mysqli_query($conn, $sql)) {
  echo "Product Added successfully, Now on to the Sizes";
} else {
  echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
              ?>

 

Upload your files as an array then use a loop to process them.

That way you process them all with a single block of code intead of giving us 4 sets of code to wade through (TLDR).

https://www.php.net/manual/en/features.file-upload.multiple.php

Secondly, do not store multiple images names in the product record.

Store them in a separate table, 1 row for each image uploaded. Then your problem with NULL values goes away - you don't insert a record if there is no image. I.E. normalize your data.

+----------------+                 +---------------------+
| product        |                 | product_image       |
+----------------+                 +---------------------+
| product_code   |-------+         | product_image_id    |
| product_name   |       +--------<| product_code        |       | 
| category       |                 | image               |
| filter         |                 +---------------------+
| description    |
| specification  |
| price          |
+----------------+

 

Thirdly, use prepared statements instead of putting datavalues directly into the queries.

<?php
              $product_code = mysqli_real_escape_string($conn, $_POST['product_code']);
              $product_name = mysqli_real_escape_string($conn, $_POST['product_name']);
              $category = mysqli_real_escape_string($conn, $_POST['category']);
              $filter = mysqli_real_escape_string($conn, $_POST['filter']);
              $description = mysqli_real_escape_string($conn, $_POST['description']);
              $specification = mysqli_real_escape_string($conn, $_POST['specification']);
              $price = mysqli_real_escape_string($conn, $_POST['price']);

              $target_dir = "../images/products/";

              if (!isset ($_FILES["img1"]["name"])) {
                $target_file1 = NULL;
            } else {
                if (!empty($_FILES["img1"]["name"])) {
                    $target_file1 = $target_dir . basename($_FILES["img1"]["name"]);
                } else {
                    $target_file1 = NULL;
                }
            }

            $uploadOk = 1;
$imageFileType1 = strtolower(pathinfo($target_file1,PATHINFO_EXTENSION));

if(isset($_POST["submit"])) {
                $check1 = getimagesize($_FILES["img1"]["tmp_name"]);

                if($check1 !== false) {
                   echo "File is an image - " . $check1["mime"] . ".";
                   $uploadOk = 1;
                 } else {
                   echo "File is not an image.";
                   $uploadOk = 0;
                 }
                 if (file_exists($target_file1)) {
                   echo "Sorry, image one already exists.";
                   $uploadOk = 0;
                 }
                 if($imageFileType1 != "jpg" && $imageFileType1 != "png" && $imageFileType1 != "jpeg"
                 && $imageFileType1 != "gif" ) {
                   echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img1.";
                   $uploadOk = 0;
                 }
                 if ($uploadOk == 0) {
                   echo "Sorry, your file was not uploaded.";
                 // if everything is ok, try to upload file
                 } else {
                   if (move_uploaded_file($_FILES["img1"]["tmp_name"], $target_file1)) {
                     echo "The file ". htmlspecialchars( basename( $_FILES["img1"]["name"])). " has been uploaded.";
                   } else {
                     echo "Sorry, there was an error uploading image one.";
                   }
                     }
                     echo '<br />';

                     }
}

$image1 = basename($target_file1);

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO products (product_code, product_name, category, filter, description, specification, img1, img2, img3, img4, price) VALUES('$product_code', '$product_name', '$category', '$filter', '$description', '$specification', '$image1', '$image2', '$image3', '$image4', '$price')";

if (mysqli_query($conn, $sql)) {
  echo "Product Added successfully, Now on to the Sizes";
} else {
  echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
              ?>

Now only one set of code to go through, i did it out this way for a reason and it was working till i fixed the mysql null issue.  I would really appreciate help with the code i've written instead of rewriting everything in a way i'm not comfortable with at the moment, i'd like to learn why this isn't working when it was.

Your coding should be

validate product data
if (valid)
    write product record

    foreach uploaded image
        validate image
        if (valid)
            write image record
        endif
    endforeach
    
endif

Are you going to tell me that isn't easier?

with respect i never said it wouldn't be easier, but i would like to learn why the code i wrote stopped working.  At a later date I will learn about arrays etc.  I didn't ask someone to help me rewrite the code, i just want to learn why what i've written stopped working, so i can learn from it.

3 hours ago, MsKazza said:

with respect i never said it wouldn't be easier, but i would like to learn why the code i wrote stopped working.  At a later date I will learn about arrays etc.  I didn't ask someone to help me rewrite the code, i just want to learn why what i've written stopped working, so i can learn from it.

If the code doesn't work, but the only solution is to use arrays then learning about arrays is probably only option? There's a reason why the code stopped working and that is you added extra conditions to the script. Instead of single images there are now multiple images? (I'm assuming and you know what they say about assuming. 😃) Learning arrays isn't that tough. It is one of the first things that is taught in any coding language.

Edited by Strider64

Here's an example using a cut-down version of your product table ...

+--------------+--------------+-------+-----------------------------+-------------------------------+------+------+
| product_code | product_name | price | img1                        | img2                          | img3 | img4 |
+--------------+--------------+-------+-----------------------------+-------------------------------+------+------+
| A001         | Widget       | 10.99 | images/products/file1.png   | images/products/file2.jpg     | NULL | NULL |
| B002         | Gizmo        |  3.49 | images/products/file3.jpg   | NULL                          | NULL | NULL |
| C003         | Wotsit       | 56.25 | images/products/file4.jpg   | images/products/file5.png     | NULL | NULL |
| D444         | Gizmo Mk II  |  2.25 | images/products/file6.png   | images/products/file7.jpg     | NULL | NULL |
+--------------+--------------+-------+-----------------------------+-------------------------------+------+------+

... and a form which submits the images as an array.

<?php
$errors = [];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    echo '<pre>', print_r($_POST, 1), '</pre>';
    echo '<pre>', print_r($_FILES, 1), '</pre>';
    
    $post = array_map('trim', $_POST);
    foreach ($post as $fn=>$v) {
        if ($v == '') {
            $errors[] = "$fn cannot be empty";
        }
    }
    
    foreach ($_FILES['img']['error'] as $k => $v) {
        if ($v != 0 && $v != 4) {
            $errors[] = "Error uploading image #$k";
        }
    }
    
    foreach ($_FILES['img']['type'] as $k => $v) {
        if (!in_array($v, ['image/png', 'image/jpeg', 'image/gif'] )
             && $_FILES['img']['error'][$k] != 4 
           ) 
        {
            $errors[] = "Image #$k is not a valid image type";
        }
    }
    
    if (!$errors) {
    
        $target_dir = "images/products";
        $uploads = [ 'img1' => null, 'img2' => null, 'img3' => null, 'img4' => null ];
        
        foreach ($_FILES['img']['name'] as $k => $filename) {
            if ($filename) {
                if (move_uploaded_file($_FILES['img']['tmp_name'][$k], $target_dir . '/' . $filename)) {
                    $uploads["img$k"]  = $target_dir . '/' . $filename;
                }
            }
        }
        
        $post = array_merge($post, $uploads);
        $stmt = $conn->prepare("INSERT INTO product 
                                (product_code, product_name, price, img1, img2, img3, img4)
                                VALUES (?, ?, ?, ?, ?, ?, ?)
                               ");
        $stmt->bind_param('ssdssss', ...array_values($post));
        $stmt->execute();
        header("Location: #");
        exit;   
    }
}
  
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Example</title>
</head>
<body>
<?php
    if ($errors) {
        echo "<div style='color:red'>" . join('<br>', $errors) . "</div>\n";
    }
?>
<form method="POST" enctype="multipart/form-data">
    Product Code<br>
    <input type="text" name="product_code">
    <br> 
    Product Name<br>
    <input type="text" name="product_name">
    <br> 
    Price<br>
    <input type="text" name="price">
    <br>
    <br>
    <fieldset>
        <legend>Product Images</legend>
        <input type="file" name="img[1]">
        <input type="file" name="img[2]">
        <input type="file" name="img[3]">
        <input type="file" name="img[4]">
    </fieldset>
    <br>
    <br>
    <input type="submit" value="Submit">
</form> 
</body>
</html>

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.