PHP Image Upload procedure

Source: Internet
Author: User

First, let's take a look at the code of the uploaded form:


<Form method = "Post" Action = "Upload. php" enctype = "multipart/form-Data">
<Table border = 0 cellspacing = 0 cellpadding = 0 align = center width = "100%">
<TD width = 55 Height = 20 align = "center"> <Input
Type = "hidden" name = "max_file_size" value = "2000000"> file: </TD>
<TD Height = "16">
<Input name = "file" type = "file" value = "">

<Input type = "Submit" value = "Upload" name = "B1">

Here are a few things to pay attention to. First, read this sentence <form method = "Post" Action = "Upload. php" enctype = "multipart/form-Data">,

Here we adopt the POST method, and some browsers also support the put method. Of course, this requires modifications to the script, which I do not recommend. Enctype = "multipart/form-data must be set in the form. In this way, the server will know that the uploaded file contains the regular form information. Remember, this is required. In addition, a hidden domain is required to limit the maximum length of the uploaded file:
<Input type = "hidden" name = "max_file_size" value = "2000000"> the name must be set

Max_file_size. Its value is the maximum length of the uploaded file. The unit is B. Here I am limited to 2 MB. Let's look at this sentence again:
<Input name = "file" type = "file" value = "">, type = "File

The file type is explained. This is the basic interface for uploading files. Next, let's talk about how to use PHP to process uploaded files. In addition, your php. the maximum length of the uploaded file set in ini may be
This affects your actual upload. Please modify it according to the actual situation. In addition, PHP Upload is first uploaded to the temporary directory, which is moved to the specified directory. The temporary directory can be modified as needed, you can also use the default value.
Okay. The form is submitted to upload. php to see what this page has:
<? PHP

/*************************************** **

Title: file upload details
Author: leehui1983 (Boss Hui)
Finish Date: 2006-12-28

**************************************** */

$ Uploaddir = "./files/"; // set the file storage directory to include/
$ Type = array ("jpg", "GIF", "BMP", "Jpeg", "PNG"); // you can specify the object type that can be uploaded.
$ Patch = "http: //"; // path of the program

// Obtain the file suffix Function
Function fileext ($ filename)
Return substr (strrchr ($ filename, '.'), 1 );
// Generate a random file name Function
Function random ($ length)
$ Hash = 'cr -';
$ Chars = 'abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxy ';
$ Max = strlen ($ chars)-1;
Mt_srand (double) microtime () * 1000000 );
For ($ I = 0; $ I <$ length; $ I ++)
$ Hash. = $ chars [mt_rand (0, $ max)];
Return $ hash;

$ A = strtolower (fileext ($ _ FILES ['file'] ['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, "<br> ";
// Generate the Object Name
Else {
$ Filename = explode (".", $ _ FILES ['file'] ['name']);
$ Filename [0] = random (10); // you can specify the length of a random number.
$ Name = implode (".", $ filename );
// $ Name1 = $ name. ". mcncc ";
$ Uploadfile = $ uploaddir. $ name;

While (file_exists ($ uploadfile ));

If (move_uploaded_file ($ _ FILES ['file'] ['tmp _ name'], $ uploadfile )){

If (is_uploaded_file ($ _ FILES ['file'] ['tmp _ name']) {
// Preview the output image
Echo "<center> your file has been uploaded. Upload image preview:
</Center> <br> <center> Src = '$ uploadfile'> </center> ";
Echo "<br> <center> <a href = 'continuing Cr failed PT: history. Go (-1) '> continue upload </a> </center> ";
Else {
Echo "Upload Failed! ";

You may be a little dizzy at first ~~, But it doesn't matter. After listening to me, you will find that this is actually the so
Easy !! First, let me talk about the principle. This program uses image uploading as an example to determine whether the file type is in the image format. If so, upload the file, rename a file with a combination of random numbers and time (avoid File Duplication)
!), Upload the file to the specified directory. After the file is successfully uploaded, the uploaded image preview is output. Here we need to explain some functions in the program. First look at return substr (strrchr ($ filename, '.'), 1)
What is the role of the strrchar () function? Let me give you an example. For example, for an image file pic.jpg, we use strrchrfor processing. strrchr(pic.jpg,'.' then, and then we will return .jpg. Do you understand? This function returns the specified character inString

The character after the last position. With substr (), we can get the JPG file, so that we can get the file suffix to determine whether the uploaded file meets the specified format. In this program, the specified format is placed in an array. You can add it as needed during actual use.
Next, let's look at the part that generates the random number file name. We can see mt_srand ()
This function is called in the manual to "play a better random number generator seed". It is actually a random number initialization function. The parameter is (double) microtime () * 1000000, if this parameter is not used, a random number is automatically set. Of course, this does not meet our needs. As a result, the random number has a certain length, ensuring that the uploaded file is not named again. Next, we call the function to determine the file type and convert it to lower case strtolower (fileext ($ _ FILES ['file'] ['name']). here is a key Dongdong $ _ files, which is a super Global Array and stores the form data to be processed. If register_globals is enabled, you can directly access it, but this is not safe. See the upload interface.

<Inputname = "file"
Type = "file" value = ""> according to the 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'] -- Obtain the object MIME type
With this information, we can easily determine the file information. Is it very convenient? ^ _ ^. Next, there are some functions that need to be understood. file_exists () -- determine whether the specified directory exists. If it does not exist, we certainly cannot upload it (it seems like it is nonsense !), Move_uploaded_file
-- Move the uploaded file to the specified directory, is_uploaded_file
-- Determine whether the file has been uploaded through http post. If the upload is successful, preview the output; otherwise, the upload fails! Success
You can use this extension, such as using JavaScript to upload multiple files, such as DZ, and Ajax to achieve no-refreshing uploads. Many blogs use this feature, finally, let's play a preview of the next two original articles.
1. I will extend this example to add the background andDatabase

To manage and review uploaded files, which will be released in the original zone.
2. Use directory functions to manage files and release them in the new zone
What you want to be interested inFriend

Watch at that time ~~~, Thank you !!!!!!

Related Article

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: 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.