Home > Article > Backend Development > Use of move_uploaded_file
Definition and Usage
move_uploaded_file() function moves the uploaded file to a new location.
If successful, return true, otherwise return false.
Syntax
move_uploaded_file(file,newloc)
Parameters | Description |
---|---|
file | Required. Specifies the files to be moved. |
newloc | Required. Specifies the new location of the file. |
Explanation
This function checks and ensures that the file specified by file is a legal upload file (that is, uploaded through PHP's HTTP POST upload mechanism). If the file is legal, it is moved to the file specified by newloc.
If file is not a legal uploaded file, no operation will occur and move_uploaded_file() will return false.
If file is a legitimate uploaded file but cannot be moved for some reason, no action will occur and move_uploaded_file() will return false and a warning will be issued.
This kind of check is particularly important if the uploaded file may cause its content to be displayed to the user or other users of this system.
Tips and Notes
Notes: This function is only used for files uploaded via HTTP POST.
Note: If the target file already exists, it will be overwritten.
Introduction from w3c, let’s talk about the problems I encountered.
Generally speaking, we will write the save file like this:
$fileName = $_SERVER['DOCUMENT_ROOT'].'/Basic/uploads/'.$_FILES['file']['name']; move_uploaded_file($_FILES['file']['tmp_name'],$fileName )
Okay, now the risk is here:
①Save the file directly.
This means that the file will not be identified in any way. If a user uploads a piece of background code and saves it with a jpg suffix or other, if the administrator accidentally maps it to php and then accesses the background, the result can be imagined. , if he deletes all databases in the background, the entire website will be directly GG. In short, saving files directly is very risky.
②Use the same file name as the user file name.
The above code will report an error if the user uses a Chinese file name.
As soon as the file name is involved, encoding is involved. If the file name is English + numbers, it is fine. If it contains Chinese, it will be a big problem and it will have to be re-encoded.
I think reliable storage should be like this:
① To identify files uploaded by users.
File recognition, this part has many functions. I think it is good to use MIME type, which is also difficult to forge.
②To change the file name.
I think it’s best to change the file name to a time format like “201634104421”, or you can also match the file name with the database.
The above introduces the use of move_uploaded_file, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.