John Beasley
John Beasley

Reputation: 3071

PHP basic upload file script

This is my first time attempting to upload a file via PHP.

Here is my HTML:

<form role="form" action="api/upload.php" id="uploadForm" method="post" enctype="multipart/form-data">
   <input id="fileToUpload" name="fileToUpload" type="file" class="file" />
   <button type="submit" name="submit" id="submit">Upload</button>
</form>

Now here is the PHP script in reference "api/upload.php":

<?php
$target_dir = "files\\";

if(isset($_POST["submit"])) {
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
}

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

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

if ($uploadOk == 0) {
echo $uploadOk . "Sorry, your file was not uploaded.";
} else {
  if (move_uploaded_file($_FILES["fileToUpload"]["name"], $target_file)) {
   echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
  } else{
     echo "Sorry, there was an error uploading your file.";
  }
} 
?>

This may be a logic error. I'm not sure. Regardless, I keep getting the message:

Sorry, there was an error uploading your file

When I echo out $uploadOk, it remains as 1. How can I find my error?

Upvotes: 1

Views: 4828

Answers (1)

Capital C
Capital C

Reputation: 329

Use $_FILES["fileToUpload"]["tmp_name"] instead of $_FILES["fileToUpload"]["name"]

Should be

move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);

Notes:-

$_FILES["fileToUpload"]["name"] is just the name of the uploaded file. $_FILES["fileToUpload"]["tmp_name"] is the temporary file that holds the content.

Hope this helps.

[Edit 1]

I was wrong about adding a value="submit" attribute to the button. name="submit" attribute is sufficient for the isset($_POST["submit")) check.

Upvotes: 2

Related Questions