Home  >  Article  >  Backend Development  >  A brief discussion on uploading files in PHP from a novice’s perspective_PHP Tutorial

A brief discussion on uploading files in PHP from a novice’s perspective_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:37:24875browse

Since I want to write a discuz plug-in, the function of this plug-in involves the function of uploading files, so I learned how to upload files in PHP from a novice's perspective.

First of all, w3cshool checked the case and felt that what he said was very detailed. Even a rookie like me understood a little bit.
Paste the address: http://www.w3school.com.cn/php/php_file_upload.asp
Following this explanation, he wrote his demo and pasted the code:
html:

This form page, as a PHP novice, let me talk about the new things I learned in this:
1.Form’s attribute enctype, Baidu translated this word and found out that this is the abbreviation of encode type, which specifies the encoding format for transmitting information to the server;
2. input’s type attribute file, this special file is uploaded;
php:
Copy code
//echo phpinfo();
//var_dump($_FILES);die;
if((($_FILES["file"]["type"]=="image/gif")||($_FILES["file"]["type"]=="image/jpeg") ||($_FILES["file"]["type"]=="image/pjpeg")) && ($_FILES["file"]["size"]<100*1024*1024)){
if($_FILES["file"]["error"]>0){
echo "Error: ".$_FILES["file"]["error"]."
";
}else{
echo "Upload: ".$_FILES["file"]["name"]."
";
echo "Type: ".$_FILES["file"]["type"]."
";
echo "Size: ".($_FILES["file"]["size"]/1024)."Kb
";
echo "Stored in ".$_FILES["file"]["tmp_name"];
}
if(file_exists("upload/".$_FILES["name"]["name"])){
echo $_FILES["file"]["name"]."already exists.";
}else{
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);
echo "Stored in: "."upload/".$_FILES["file"]["name"];
}
}else{
echo "Invalid file";
}
Copy code
When debugging this demo, I encountered a problem: when running this demo, PHP reported a warning, indicating that the upload was unsuccessful.
At this time, I wanted to print out the $_FILES variable to take a look. When I printed it out, I found error=1; only then did I know that the uploaded file exceeded the upload file size of php.ini, causing the upload to fail.
Here are my new knowledge points:
 
Copy code
Common usage of $_FILES system function in PHP programming language are:
 $_FILES['myFile']['name'] displays the original name of the client file.
 $_FILES['myFile']['type'] The MIME type of the file, such as "image/gif".
 $_FILES['myFile']['size'] The size of the uploaded file, in bytes.
 $_FILES['myFile']['tmp_name'] The name of the temporary file stored, usually the system default.
 $_FILES['myFile']['error'] This is the error code related to file upload. The following are the meanings of different codes:
 0; File uploaded successfully.
 1; The file size exceeds the size set by the system in php.ini.
 2; File size exceeded
 The value specified by the MAX_FILE_SIZE option.
 3; Only part of the file was uploaded.
 4; No files were uploaded.
 5; The uploaded file size is 0.
Copy code
At this point, you should know what caused the error I just ran the demo. Since I found that the limit in php.ini was exceeded, I then modified the configuration of php.ini.
To summarize my feelings about modifying this php.ini upload limit:
First of all, to modify the size limit of PHP upload files, you need to change two parameters in php.ini, one is upload_max_filesize, and the other is post_max_size. Just modify the sizes of these two parameters!
The second step is to find the location of php.ini. Since my local computer is an integrated environment, php.ini is under the apache folder. If it is an environment built by myself, it will be under the php folder. If Can't find it, echo phpinfo(), you can see the location of the php.ini file.
That’s it, novices like me can run the demo on w3cshool and complete the uploading of the instance.
Regarding uploading files, I took a look at the plug-ins developed by other plug-in authors of discuz, and found some small gains. I will post them here to share with you:
Copy code
$fileTypes = array('mp3','wav'); //Define the file types allowed to be uploaded
$result = null;
$uploadDir = './mail'; //Upload path
if(!submitcheck($_POST['formhash2'])){ //Check whether the file is uploaded
if($_POST['upname']==''){ //Determine whether the name of the uploaded file is empty
$result=lang('plugin/saya_mails', 'noname');
}else{
                                                                                                                                                                      $myfile = $_FILES['myfile']; //Get uploaded file information
                  $myfileType = substr($myfile['name'], strrpos($myfile['name'], ".") + 1); //Two ways to get the suffix name of the uploaded file
                                                                                                                                                                               
                                                                                                                                                                                                                                                                       
                      $result = lang('plugin/saya_mails', 'big');
          } else if (!in_array($myfileType, $fileTypes)) { //Determine whether it is a type that is allowed to be uploaded
                      $result = lang('plugin/saya_mails', 'type');
          } elseif (is_uploaded_file($myfile['tmp_name'])) { //Determine whether the file is uploaded through HTTP post
                                                                                                $toFile = './source/plugin/saya_mails/mail/' . $myfile['name'];
if (@move_uploaded_file ($ myfile ['tmp_name'], $ tofile) {// Copy the file to the target storage address@是@是 //                                                                                                                                                                                                                                                                                                  
                      $end=0;
                          $result = lang('plugin/saya_mails', 'success');  
          } else {
                        $result = lang('plugin/saya_mails', 'unknow');
          }
        } else {
                      $result = lang('plugin/saya_mails', 'big');
        }
 }
 }
Copy code
After comparing the upload examples on w3cshool, I feel that this author’s writing is more complete
The general process is:
1. Determine whether the file is uploaded. The method he uses is built-in with discuz. We generally use it to determine whether the value of the hidden parameter passed by the form exists;
2. Determine whether the name of the uploaded file is empty. You can skip this step. This is just an input he wrote himself;
3. Determine whether the upload size is exceeded;
4. Get the file suffix name and determine whether it is an allowed upload file type;
5. Determine whether the file is uploaded through http post;
6. Move saved files;
Regarding the above process, I personally summarized the new knowledge points I gained:
1. Regarding obtaining the suffix name of the file, the original plug-in author used the function strrpos() to return the location of ".", and then intercepted the function substr() to obtain the suffix of the uploaded file.
Here, the strrpos() function, my own understanding should be the abbreviation of string return position, of course I haven't checked it yet! This function returns the position of the last occurrence of the string to be found in the string, and returns this position. That is, check from back to front to find the position where it first appears. Reference address: http://www.w3school.com.cn/php/func_string_strrpos.asp
  The original author used this method to judge. It is definitely possible. I searched on Baidu and found that this method can also be implemented by cooperating with the strrchr() and substr() functions. I commented the method I thought of above. It’s in the source code. In fact, it’s almost the same. The strrchr() function returns the string from the last occurrence of the string to be searched to the end. Reference address: http://www.w3school.com.cn/php/func_string_strrchr.asp
Use the above two methods to determine whether the type of uploaded file meets the standard, instead of judging by $_FILES["file"]["type"]. This is a better judgment point for novices, because as long as you print $ You already know the _FILES parameter, but the type attribute is not so clear to judge.
2. Use is_uploaded_file() to determine whether the file is uploaded via http
3. The @ in front of move_uploaded_file() is used to block error messages and warnings

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/735883.htmlTechArticleI want to write a discuz plug-in. The function of this plug-in involves the function of uploading files, so I use it as a rookie. Let’s take a look at how to upload files using PHP. First, w3cshool checked the case...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn