lacking-cypher
lacking-cypher

Reputation: 580

PHP Uploading file unsuccessful

I'm trying to upload a file to my local server, but it keeps being unsuccessful.

All my files are inside /var/www/html/ However I made a folder called uploads in the html folder, and I changed its permissions to 777 (what I took on average from searching was the best for my needs)

this is my code: index.html

<!DOCTYPE html>
<html>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>

upload.php

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES['fileToUpload']['name']);
echo "Target File: " . $target_file . "<br />";

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).  " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}
?>

Upvotes: 0

Views: 371

Answers (3)

Umair Ayub
Umair Ayub

Reputation: 21201

Your Input file is

<input name="uploadedfile" type="file" />

so change $_FILES['fileToUpload']['name'] to $_FILES['uploadedfile']['name']

$_FILES['uploadedfile']['name'] Must have the value of Name attribute of your file field

Upvotes: 1

Jason Bassett
Jason Bassett

Reputation: 1291

Try This:

index.html

 <!DOCTYPE html>
 <html>
 <body>
 <form enctype="multipart/form-data" action="upload.php" method="POST">
 Choose a file to upload: <input name="uploadedfile" type="file" /><br />
 <input type="submit" value="Upload File" />
 </form>
 </body>
 </html>

upload.php

if(isset($_FILES["uploadedfile"]["type"]) && ($_FILES["uploadedfile"]["size"] < 5000000)){
      $sourcePath = $_FILES['uploadedfile']['tmp_name'];
      $file = $_FILES['uploadedfile']['name'];
      $targetPath = "/uploads/".$file;
      if(move_uploaded_file($sourcePath,$targetPath)){
      echo "The file: ".$_FILES['uploadedfile']['name']." has been uploaded";
   }else{
      echo "Looks like it failed.";
   }
}else{
   echo "You forgot to select a file, or the file size is too large.";
}

So what this does is checks if a file exists and checks if it's smaller than 5MB. If so it moves on to the upload part.

Upvotes: 0

tihox1
tihox1

Reputation: 54

You didn't set the variable

$target_path

you meant but not used

$target_file

instead.

Upvotes: 0

Related Questions