PHP file upload main code explanation

  • 2020-10-23 20:03:38
  • OfStack


<?php   
 if($_FILES['myfile']['name'] != '') {   
if($_FILES['myfile']['error'] > 0) {   
echo " Error status: " . $_FILES['myfile']['error'];   
} else {   
move_uploaded_file($_FILES['myfile']['tmp_name'] , "uploads/" . $FILES['myfile']['name']);   
echo "<script>alert( Upload successful! );</script>";   
}   
} else{   
echo "<script>alert( Please upload the file! );</script>";   
}   
?> 

Description:

Before we explain this code, it is important to know the following.

$_FILES['myfile']['name'] is the name of the file being uploaded
$_FILES['myfile']['type'] refers to the type of file being uploaded
$_FILES['myfile']['size'] is the size of the file to be uploaded in bytes (B)
$_FILES['myfile']['tmp_name'] refers to the name of the temporary copy of the uploaded file stored on the server. The immediate file will be automatically destroyed after the file is moved to the specified directory.
$_FILES['myfile']["error"] refers to the error status code that may appear on the file upload, as explained later on the meaning of each status.

With this in mind, let's take a look at the 1 upload.php code.

First of all, the myfile in $_FILES['myfile']['name'] refers to the name value of the file tag uploaded on the HTML page above, so we can know which input submitted the file we are working on.

Then we can determine whether the 1 $_FILES['myfile']['name'] is not empty. From this we can know whether the user has uploaded a file to perform different actions.

If the file is uploaded and its status is 0, the file is uploaded successfully. We can use the move_uploaded_file method to store the uploaded file in the specified directory. In this example, the uploaded file is moved to the uploads folder in the same directory, which is relative to the PHP file (i.e. upload.php).

For example, if we want to move the uploaded file to a folder called user on the first layer of upload.php, we can write this: move_uploaded_file ($_FILES['myfile']['tmp_name'], "./user/". $FILES['myfile']['name']).


Related articles: