简体   繁体   中英

How to upload photos/file to server using PHP

Hi so I'm trying to allow users to upload a photo to a listing. I'm using dropzone.js and I have the form done, it works perfectly! except that photos don't actually upload to the folder "uploads/"

I have tried many many different ways spent days researching and I cannot for the life of me figure out what is wrong.

Kindly note that it is a multipage form so I cannot post the whole form on here but ill try to share the important scripts!

Dropzone code:

  <head>
  <script src="https://unpkg.com/dropzone@5/dist/min/dropzone.min.js"></script>
  <link rel="stylesheet" href="https://unpkg.com/dropzone@5/dist/min/dropzone.min.css" type="text/css" />
</head>

    <div class="container" >
        <div class='content'>
        <form action="create.php" method="post" type="file" name="file" class="dropzone" id="dropzonewidget" enctype="multipart/form-data">
       
    </div> 
  </div>
  </div>
    </div>

    <div class="row form-block flex-column flex-sm-row">
      <div class="col text-center text-sm-start"><a class="btn btn-link text-muted" href="user-add-2.php"> <i class="fa-chevron-left fa me-2"></i>Back</a>
      </div>
        <div class="col text-center text-sm-end"><button type="submit" name="save" class="btn btn-primary">save</button><i class="fa-chevron-right fa ms-2"></i></div>
      </form>

Now for the PHP script: I have 2 attempts that got close, the first actually makes its way into the database and the second just echo's all error scripts

Script 1: (kinda works)

 $uploadDir = 'var/www/uploads';
 $tmpFile = $_FILES['file']['tmp_name'];

 // upload file to directory
 $fileName = $uploadDir.'/'.time().'-'. $_FILES['file'] 
 ['name'];
 move_uploaded_file($tmpFile,$fileName); {

 
 $sql = "INSERT INTO hosts(id, user_name, name, type, 
 country, city, state, zip, about, price, photo)
  VALUES('$id', '$user_name', '$name', 
 '$type', '$country', '$city', '$state', '$zip', 
 '$about', '$price', '$fileName')";

Script 2:

 $target_dir = "uploads/";
 $target_file = $target_dir . basename($_FILES["file"] 
 ["name"]);
 $uploadOk = 1;
 $imageFileType = 
 strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

 // Check if image file is a actual image or fake image

 $check = getimagesize($_FILES["file"]["tmp_name"]);
 if($check !== false) {
  echo "File is an image - " . $check["mime"] . ".";
  $uploadOk = 1;
 } else {
  echo "File is not an image.";
  $uploadOk = 0;
  }


  // Check if file already exists
  if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
  }

  // Check file size
   if ($_FILES["file"]["size"] > 1000000) {
    echo "Sorry, your file is too large.";
   $uploadOk = 0;
   }

   // Allow certain file formats
   if($imageFileType != "jpg" && $imageFileType != "png" 
   && $imageFileType != "jpeg"
   && $imageFileType != "gif" ) {
   echo "Sorry, only JPG, JPEG, PNG & GIF 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["file"]["tmp_name"], 
   $target_file)) {
   echo "The file ". htmlspecialchars( basename( 
   $_FILES["file"]["name"])). " has been uploaded.";
   //$pictureName = "uploads". basename( 
   $_FILES["fileToUpload"]["name"]);
   } else {
   echo "Sorry, there was an error uploading your 
   file.";
   }

At the end of both of these attempts I have a simple insert query (ps I know about SQL injections, just trying to get it to work first.)

hope I didn't give you a headache

Just a heads up I am new to PHP and to SO so be kind and I hope a more experienced developer can help me out of these troubling times, Thanks in advance: and if you understand my issue please post some code not a vague response :) cheers

For dropzone uploads (multiple file uploads)

a. you do NOT need to specify enctype="multipart/form-data" and method="post" type="file" name="file"

b. No need to use submit button

c. As stated before, make sure there is a sub-folder known as uploads and it is write-permitted

d. To do further db maninpulation (eg insert), execute the insert query in the php, make sure using $_FILES['file']['name'] when constructing the insert query

Hence, please amend your code to:

HTML

<head>
  <script src="https://unpkg.com/dropzone@5/dist/min/dropzone.min.js"></script>
  <link rel="stylesheet" href="https://unpkg.com/dropzone@5/dist/min/dropzone.min.css" type="text/css" />
</head>

    <div class="container" >
        <div class='content'>
        <form action="create.php" class="dropzone" id="dropzonewidget">
       </form>
    </div> 
  </div>

create.php

<?php
$target_dir = "./uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir.$_FILES['file']['name'])) {
   $status = 1;

// do further update in database
// please note that the file name is $_FILES['file']['name']
// make sure you use parametized prepared statement in your insert query
// to avoid SQL injection attacks
//
}
?>

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