Home >Backend Development >PHP Tutorial >Detailed explanation of PHP file upload examples! ! ! _PHP Tutorial

Detailed explanation of PHP file upload examples! ! ! _PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:58:52850browse

First, let’s take a look at the form code for the upload part:

Copy the code The code is as follows:


                                                                     ="B1">                                                                                   How many Something to pay attention to, first look at this sentence , here we use the POST method, some browsers also support the PUT method , of course this requires modifying the script, which I don't recommend. Enctype="multipart/form-data must be set in the form, so that the server knows that the uploaded file contains regular form information. Remember, this must be set. In addition, a hidden field is needed to limit the maximum length of the uploaded file: < ;input type="hidden" name="MAX_FILE_SIZE" value="2000000">, here name must be set to MAX_FILE_SIZE, the value is the maximum length of the uploaded file, the unit is B, here I limit it to 2M. :, type="file" indicates the file type. In this way, a basic file upload interface is completed. Next, let’s talk about how to use PHP to process uploaded files. In addition, the maximum length of uploaded files set in your php.ini may affect your actual upload. Please modify it according to the actual situation. In addition, PHP uploads are first transferred to the temporary directory and then moved to the specified directory. Yes; the temporary directory can be modified as needed, or the default value can be used.
Okay, submit the form upload.php and see what is on this page:

The PHP code is as follows:




Copy code
The code is as follows:
/*****************************************
Title: Detailed explanation of file upload
Author:leehui1983(Hui Boss)
Finish Date:2006-12-28
******************************* **************/
$uploaddir = "./files/";//Set the file saving directory. Note the inclusion of /
$type=array("jpg ","gif","bmp","jpeg","png");//Set the types of files allowed to be uploaded.
$patch="http://127.0.0.1/cr_downloadphp/upload/files/"; //The path where the program is located

//Function to get the file suffix name
function fileext($filename)
{
return substr(strrchr($filename, '.'), 1);
}                                                                                      NOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
$ MAX = Strlen ($ Chars) -1;
Mt_srand (Double) microtime ()*1000000);
for ($ i = 0; $ length; $ i ++)
{<> $ Hash. = $ Chars [mt_rand (0, $ max)];
}
Return $ hash;
}
$ a = Strtolower (FileExt ($ _ files ['files [' files ['files [' files ['files [' files ']['name']));
//Determine the file type
if(!in_array(strtolower(fileext($_FILES['file']['name'])),$type))
{
$text=implode(",",$type);
echo "You can only upload the following types of files: ",$text,"
"; > //Generate the file name of the target file                                                                                                     >           $filename[0]=random(10); //Set the random number length                                                                                                                               
             $uploadfile=$uploaddir.$name;                                        
while(file_exists($uploadfile));
if (move_uploaded_file($_FILES['file']['tmp_name'],$uploadfile)){

if(is_uploaded_file($_FILES[ 'file']['tmp_name'])){
//Output image preview
center>";      ;Continue uploading";
                                                                                                                                         >

You may be a little dizzy when you first read these~~, but it doesn’t matter, listen to me and you will find that this thing is actually SO EASY! ! First, let me explain the principle. This program takes uploading pictures as an example. It first determines whether the file type is an image format. If so, it uploads the file and renames the file with a combination of random numbers and time (it is necessary to avoid uploading files with duplicate names. ! ), and then upload the file to the specified directory. If the upload is successful, a preview of the uploaded image will be output. Here are some explanations of some functions in the program. Let’s first look at return substr(strrchr($filename, '.'), 1). What is the role of the strrchar() function? Let me give you an example and everyone will know, such as a picture file pic.jpg. We use strrchr to process it. strrchr( pic.jpg,'.'), it will return .jpg, got it? This function returns the character following the last occurrence of the specified character in the string. With substr() we can get jpg, so we can get the file extension to determine whether the uploaded file meets the specified format. This program puts the specified format in an array, which can be added as needed during actual use.
Next, look at the file name that generates random numbers. We see the function mt_srand(). The manual calls it "sowing a better random number generator seed". It is actually a function that initializes a random number. The parameters It is (double)microtime() * 1000000. If this is not a parameter, a random number will be automatically set. Of course, this does not meet our needs. In this way, the random number will have a certain length, ensuring that the uploaded file is not duplicated. name. Next, we call the function to determine the file type and convert it into lowercase strtolower(fileext($_FILES['file']['name'])). There is a very critical thing here $_FILES, which is a super global The array stores the form data that needs to be processed. If register_globals is turned on, it can also be accessed directly, but this is unsafe. Look at the upload interface just now , based on this form name, we can get a lot of information:
$_FILES['file']['name ']--Get the file name
$_FILES['file']['tmp_name']--Get the temporary storage location
$_FILES['file']['size']--Get the file size
$_FILES['file']['type']--get the file MIME type
With this information, we can easily determine the file information. Isn't it very convenient? ^_^, there are some functions that need to be understood next, file_exists()--determine whether the specified directory exists. If it does not exist, of course we cannot upload it (it seems like nonsense!), move_uploaded_file--move the uploaded file to the specified directory, is_uploaded_file- - Determine whether the file has been uploaded via HTTP POST. If the upload is successful, we will output the preview, otherwise the output upload will fail! You're done
You can expand based on this, such as using JS to achieve multi-file upload, such as the upload effect of DZ, and then combining it with AJAX to achieve refresh-free upload. Many blogs have adopted it. Finally, play the next two original articles. Preview
1 I will expand this example, add backend and database parts, realize uploaded file management and review, and will publish it in the original area.
2 Use directory functions to achieve file management and will be published in the novice area
I hope interested friends will watch it~~~, thank you! ! ! ! ! !

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317506.htmlTechArticleFirst look at the form code of the upload part: Copy the code as follows: formmethod="post"action="upload .php"enctype="multipart/form-data" tableborder=0cellspacing=0cellpadding=0al...
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