Parsing of PHP's Move_uploaded_file () function

Source: Internet
Author: User
This article mainly introduces the PHP move_uploaded_file () function, in fact, is to move the uploaded files to a new location, the need for friends can refer to the next

Definition and usage

move_uploaded_file()function to move the uploaded file to a new location.

Returns true if successful, otherwise false is returned.

Grammar

Move_uploaded_file (File,newloc)

Parameters Description
File Necessary. Specifies the files to be moved.
Newloc Necessary. Specify a new location for the document.

Description

This function checks and ensures that files specified by file are valid upload files (that is, uploaded via PHP's HTTP POST upload mechanism). If the file is valid, move it to the file specified by Newloc.

If file is not legitimately uploaded, no action will occur and Move_uploaded_file () will return false.

If file is a legitimate upload, but for some reason it cannot be moved, nothing happens, Move_uploaded_file () returns false, and a warning is issued.

This check is especially important if the uploaded file is likely to cause the user or other users of the system to display its content.

Hints and Notes

Note: This function is only used for files uploaded via HTTP POST.

Note: If the destination file already exists, it will be overwritten.

Security Supplement

From the introduction, the following talk about the problems I encountered.

In general, we do this by writing the save file:

$fileName = $_server[' Document_root '). ' /basic/uploads/'. $_files[' file ' [' Name ']; Move_uploaded_file ($_files[' file ' [' Tmp_name '], $fileName)

First of all, the meaning of these two lines of code: Save the file directly, and the file name is also the file name uploaded by the user
Okay, here's the risk:

① Save the file directly.

This means that the file does not have any recognition, if there is a user upload a piece of background code saved as a JPG suffix or other, if the administrator does not pay attention to the PHP map, and then access to the background,-the result is conceivable, if he in the background to delete all databases, the entire site directly GG. In short, there is a great risk of directly saving files.

② uses the same file name as the user's file name.

The above code if the user uses the Chinese file name, will be an error.

One involves the file name, it involves the code, if the file name is English + number is OK, if it contains Chinese that is big, to re-encode it.

I think the reliable preservation should be like this:

① to identify the files uploaded by the user.

File recognition, this part has a lot of features, I think the MIME type is very good, this is difficult to forge.

② to change the file name.

I think it's best to change the format of time to a file name like "201803264104421", or you can associate a file name with a database.

Add:

There are two parameters, the first parameter is the temporary file name after you upload, automatically generated by the system. Usually the style is:

$_file["FILE" ["Tmp_name"];

Where file is the name of your foreground document upload form.
The second parameter is a new file name that contains a path. Such as:

"Upload/1.jpg";

In this way, you will move your uploaded files to the subdirectory under the name upload in the current directory, and save the file name as: 1.jpg.

Move_uploaded_file () Function instance

Use the Move_uploaded_file () function to upload files to the server.

<?php  $tmp _filename = $_files[' myupload ' [' tmp_name '];  if (!move_uploaded_file ($tmp _filename, "/path/to/dest/{$_files[' myupload ' [' Name ']}") {   echo "an error had occurred moving the uploaded file.<br> ";   echo "Ensure that if safe_mode are on the". " UID PHP is using matches the file. ";   Exit;  } else {   echo "The file has been successfully uploaded!";  }? >

Move_uploaded_file upload file failure cases and solutions

There was a problem with implementing a PHP script that uploads the avatar image file when the user registers: The PHP script code looks like this:

<?php define (' ROOT ', DirName (__file__). ' /');  if ($_files["file" ["error"] > 0)  {   echo "Return Code:". $_files["File" ["Error"]. "<br/>";  }  else  {   echo "Upload:". $_files["File" ["Name"]. "<br/>";   echo "Type:". $_files["File" ["type"]. "<br/>";   echo "Size:". ($_files["File" ["Size"]/1024). "Kb<br/>";   echo "Temp file:". $_files["File" ["Tmp_name"]. "<br/>";   if (file_exists ("upload/". $_files["File" ["Name"]))   {    echo $_files["file" ["Name"]. "already exists.";   }   else   {    if (is_uploaded_file ($_files[' file '] [' tmp_name '])) {     $stored _path = ROOT. ' /upload/'. basename ($_files[' file ' [' name ']);          if (move_uploaded_file ($_files[' file ' [' Tmp_name '], $stored _path)) {      echo "stored in:". $stored _path;     } else{      Echo ' Stored failed:file save error ';     }    } else{     Echo ' Stored failed:no post ';}}  }?>

When I execute the script above, the script outputs "Stored Failed:file Save Error", which is obviously an error. I saw an error in the Php_error_log file: Insufficient permissions, I finally found the wrong place: we store the image of the destination directory for PHP users do not have permission to execute PHP script users and I write script code, create picture folder user is not the same user, so only need to change the file permissions to 777.

PHP Development Learning File Upload (move_uploaded_file)

Function: To move the temporary files uploaded to the upload directory, upload is in the root directory has been created!!!

<form action= "" enctype= "Multipart/form-data" method= "post" name= "UploadFile" > Upload file: <input type= "File" name= "Upfile"/><br> <input type= "Submit" value= "upload"/></form> <?php//print_r ($_FILES["Upfile"]); if (Is_uploaded_file ($_files[' upfile ' [' tmp_name '])) {$upfile =$_files["upfile"];//Gets the value inside the array $name = $upfile ["Name"] ;//The file name $type = $upfile ["type"];//upload the file $size = $upfile ["Size"];//upload the file $tmp _name= $upfile ["Tmp_name"];//    Upload the file temporary storage path//Determine whether the picture switch ($type) {case ' image/pjpeg ': $okType =true;   Break    Case ' image/jpeg ': $okType =true;   Break    Case ' image/gif ': $okType =true;   Break    Case ' image/png ': $okType =true;  Break if ($okType) {/** * 0: File Upload succeeded <br/> * 1: Exceeded file size, set in php.ini file <br/> * 2: Exceeded file size max_file_size option specified value <br/> * 3: File is only partially uploaded <br/> * 4: No file is uploaded <br/> * 5: The file size of the upload is 0 */$error = $upfile ["Error"];//the system returns after uploading   Return the value of echo "================<br/>"; echo "Upload file name is:". $name. " <br/> "; echo "Upload file type is:". $type. "   <br/> "; echo "Upload file size is:". $size. "   <br/> "; echo "The value returned by the system after uploading is:". $error. "   <br/> "; echo "The temporary storage path for uploading files is:". $tmp _name. "    <br/> "; echo "Start moving upload file <br/>"; Move the uploaded temporary files to the upload directory (upload is already created in the root directory!!!   ) Move_uploaded_file ($tmp _name, "upload/". $name);   $destination = "upload/". $name;   echo "================<br/>";   echo "Upload information:<br/>"; if ($error ==0) {echo "File uploaded successfully!    ";    echo "<br> picture preview:<br>"; echo " "; echo "alt=\" Picture preview: \ r file name: ". $destination."   \ r upload time: \ ">";   }elseif ($error ==1) {echo "exceeds file size, set in php.ini file";   }elseif ($error ==2) {echo "exceeds the value specified by the file's size max_file_size option";   }elseif ($error ==3) {echo "file is only partially uploaded";   }elseif ($error ==4) {echo "No files were uploaded";   }else{echo "Upload file size is 0"; }}else{echo "Please upload pictures in jpg,gif,png and other formats!"  "; }}?>

Execution Result:

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.