'How to upload file in a target folder with php?



I am new to PHP and learning it!
I have created a simple database on my localhost name 'submitpaper'
Then I have created a table name 'upload_file' having two fields (file1, file2) both are (VARCHAR 255)
I am having problem in saving files to target folder 'testupload'

Kindly Check and Review My PHP Script And HTML

PHP Script

<?php   
//This is the directory where files will be saved  
$target = "testupload/";
$target = $target . basename( $_FILES['file']['name']);

//This gets all the other information from the form  
$file1=($_FILES['file1']['name']);
$file2=($_FILES['file2']['name']);

// Connects to your Database  
mysql_connect("localhost", "root", "")
//Writes the information to the database
mysql_query("INSERT INTO `upload_file` VALUES ('$file1', '$file2')") ;

//Writes the photo to the server
if(move_uploaded_file($_FILES['file']['tmp_name'], $target))  {
//Tells you if its all ok  
echo "The file ". basename( $_FILES['uploadedfile']['name']). "has been uploaded,        and your information has been added to the directory";  }
else {   
//Gives and error if its not  echo "Sorry, there was a problem uploading your file.";      }

?>

HTML FILE CODE

<html>
<body>

<form action="upload_file.php" method="post"
 enctype="multipart/form-data">
File1:<input type="file" name="file1" id="file1"><br>
File2:<input type="file" name="file2" id="file2">
<input type="submit" name="submit" value="Submit">
</form>

</body>



Solution 1:[1]

You are trying to access the file name incorrectly in $_FILES['file']['name']. You have to use like $_FILES['nameoffile']['name'] where nameoffile is the name of the file you have given for the file input field. ie as,

$_FILES['file1']['name']

CODE:

$target = "testupload/";
$target = $target . basename( $_FILES['file1']['name']);
if(move_uploaded_file($_FILES['file1']['tmp_name'], $target)) 
{
}

Solution 2:[2]

The following code may useful for you.

$target = "Admin/upload/";
$target = $target . basename( $_FILES['uploaded_file']['name']); 
$pic=($_FILES['uploaded_file']['name']); 
//Writes the photo to the server 
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target)) 
{ 
    //Tells you if its all ok 
    //echo "The file ". basename( $_FILES['uploaded_file']['name']). " has been uploaded, and your information has been added to the directory"; 
} 
else 
{ 
    //Gives and error if its not 
    //echo "Sorry, there was a problem uploading your file."; 
} 

Before that you have to Read and Write permission for the file upload path folder.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jenz
Solution 2 Phoenix