PHP file upload and security

Source: Internet
Author: User
Tags php file upload
Inputtypefilenameupload: Click Upload to select a file and submit the form to the php program. At this time, the file will be uploaded to the specified location, but the file will not be uploaded to the website directory and cannot be accessed. What should I do? copy the file to co

Inputtype = "file" name = "upload"/display effect: Click upload to select a file and submit the form to the php program. The upload process is complete. At this time, the file will be uploaded to the specified location, but the file will not be uploaded to the website directory and cannot be accessed. What should I do? copy the file to co

The display effect is as follows. Click Upload and select FileAfter that, submit the form to the php program and complete the upload process. This time FileIs uploaded to the specified location, FileUploading is useless here FileIf you no longer upload files in the website directory and cannot access them, what should you do? copy the file to the copy function, which can help us solve this problem. The function prototype is copy (Source FilePath, the path to save) different php environments have different upload paths. What should we do? We cannot determine the location of the upload directory. In this case, we will use a predefined variable $ _ FILES and $ _ POST. The difference is that for file-type forms, we try to print the result as follows Array ([upload] => Array ([name] => record .docx [type] => application/vnd.openxmlformats-officedocument.wordprocessingml.doc ument [tmp_name] => C: \ Windows \ Temp \ php2AB9. tmp [error] => 0 [size] => 16113 )) the returned result is a two-dimensional array. upload is the name specified in the file form. This is the same as post, but the data volume contained in the file is much larger. name FileName type FileType tmp_name in temporary FileThe folder path error information size in the Array error will return some error information in octal, in total, 0 1 1 2 3 4 5 6 7 detailed introduction in the php Manual

UPLOAD_ERR_ OK
The value is 0 and no error occurs,FileUpload successful.

UPLOAD_ERR_INI_SIZE
The value is 1.FileThe value exceeds the limit of the upload_max_filesize option in php. ini.

UPLOAD_ERR_FORM_SIZE
The value is 2. UploadFileThe size exceeds the value specified by the MAX_FILE_SIZE option in the HTML form.

UPLOAD_ERR_PARTIAL
The value is 3,FileOnly partially uploaded.

UPLOAD_ERR_NO_FILE
The value is 4, noFileUploaded.

UPLOAD_ERR_NO_TMP_DIR
The value is 6 and the temporary value cannot be found.FileFolder. PHP 4.3.10 and PHP 5.0.3 are introduced.

UPLOAD_ERR_CANT_WRITE
The value is 7,FileWrite failed. PHP 5.1.0 is introduced.

Error 5: it has been abandoned now. If we want to judgeFileWhether the file is successfully uploaded can be determined by the error value. Because the file is a two-dimensional array, We need to write $ _ FILES ['upload'] ['error'].

Tmp_name is uploadedFileCurrent location andFileWe need to create a new location to fully includeFileIf we need to maintainFileWe can get the name through $ _ FILES ['upload'] ['name. The path to be uploaded is customized.

 FileCopy to the current directory ($ _ FILES ['upload'] ['tmp _ name'], $ path );}

The two most basic upload processes ..

The first process is to use a form with file and clear data, selectFileAnd submit it to PHP. We cannot intervene in this process.

In the second process, we have uploadedFile, Copy to the place we want to save.

If it is not copied, PHP will automatically destroyFile. When to modify the default uploadFileFolder Location SystemSecurityWhen the level is relatively high.

We usually see images uploaded successfully on other websites. It is not displayed after an upload .. This is what we see after copying, becauseFileAttackers can access the website through http only in the directory of the website. However, some hackers will use our upload program to upload malicious things or forge files. The upload actually points to a certain php program. When the program runs the process will copy one of our php programs. TxtFileIn this way, hackers can download thisFileThe purpose of viewing our php source code has been achieved in order to find the vulnerability to ensure that our programSecurityWe makeFileInstead of using the copy program, we recommend that you use the move_uploaded_file function specified by php. The difference between move_uploaded_file and copy is that move_uploaded_file must be submitted and uploaded through form submission.File. Move_upload: If a hacker successfully uploads a. php fileFileHe canFileWrite malicious code in it to intrude into our servers. We need to impose some restrictions. The common thing is to remove the extension, you can use $ _ FILES ['upload'] ['name'] to obtain the originalFileName, which is the best segment for string extensions that are separated by dots $ ext = end (explode ('. ', $ _ FILES ['upload'] ['name']) after obtaining the extension, we can determine if ($ ext = "php") die ('upload prohibited to PHPFile'); But this is not a good way to prohibit it.FileToo many

However, we can consider it. When will we allow users

UploadFile.
The member system needs to upload the Avatar
Photo Album upload
Document must be allowed to upload various document classesFileIt is better to define what type of upload is allowed.FileCode writing is simpler.

Images include jpg, jpeg, gif, png, and bmp.

Doc, docx, xls, xlsx, ppt, pdf

WhenFileWhen the name contains special characters. It may cause us to be unable to access the uploadedFile.

To avoid possible problems, we recommend that you rename the file after uploading.FileName.

Uploaded using the rename FunctionFileHow to save the image to the database? In our analysis, if the user uploads images, our ultimate goal is to display images on the website.

The HTML code is used to display images on the webpage.

Click Download. The link is used.
FilePath "> download

That is to say, the"FilePath "ratherFileThis means that we only need to saveFileYou can display the corresponding path to html during the display, and you do not need to uploadFileSave content to the databaseFileUpload is a dangerous operation. If you write code accidentally, it will be easily exploited by others with ulterior motives. In fact, there are still many problems.Security.

HoweverSecurity. We can all perform layer-by-layer checks. To avoid it as much as possible. But it can only be avoided. Why .. In fact, variousSecurityMeans. The main purpose at the beginning was not to prevent hacker intrusion. It prevents user error operations. What should I do if I want to find a method to intrude into the website and can be understood as wrong operations including GET POST COOKIE and so on, but these operations are inevitable? This problem has been discussed for a long time, that is, do not trust any user input. That is to say, any communication method with the outside world must be carried out.SecurityIt is absolutely true that the value in each transferred volume must have a permitted range. For example, if we flip the page $ _ GET ['page'], its value must be the minimum first of the int type. the maximum page size, that is, the total number per page. Then we can restrict the forced conversion of the page into an integer to determine the size of the number, it is not recommended to pass complex data such? SQL = where id = 12 then in the php code $ SQL = "select * from indicates. $ _ GET ['SQL']" there is no difference between this writing method and finding the dead

Would you prefer? Id = 12
PHP code
$ Id = (int) $ _ GET ['id'];
$ SQL = "select * from table name where id = '$ id '";

If the data source is external submission, you must remember to follow the scope of your program execution. Strictly judge the amount submitted by the user. And try to be an accurate value instead of adding any expression to the data submitted by the user. Perform a strict formatting check. At least, we can ensure our program. In case of unexpected error operations, you canSecurity. For example, if the conversion type is converted to the format and then involved in the php operation, there is also a quotation mark problem here. Our common query methods are as follows:

This is usually the case

$ Key = $ _ GET ['key'];
$ SQL = "select * from table name where id = '$ key '";

Or identity verification.

$ SQL = "select * from table name where user = '$ user '";

What will happen if someone maliciously submits a single quotation mark at this time. Assume that I submit test 'or 1 = '1'.

Then substitute the code. The final SQL statement is

Select * from table name where user = 'test' or 1 = '1'

This means that no matter what user name he submits. All have query results ..

To prevent this situation. We should check the content submitted by the user. Whether it contains invalid characters. However, you must enter quotation marks. We should use \ In some PHP environments, this Auto conversion quotation mark is not opened

If (! Get_magic_quotes_gpc ()){
$ Lastname = addslashes ($ _ POST ['lastname']);
} Else {
$ Lastname = $ _ POST ['lastname'];
}

Provided by the PHP Manual

Get_magic_quotes_gpc ()
This function can be used to read whether the Automatic Quotation Mark escape Function in PHP configuration is enabled.

The addslashes function can be used to process quotation marks in "quantity. Without an escape character. Add.

If it is enabled, it means that the content is relativeSecurity. It can be used directly.

There is anotherSecurityProblem. This problem is common in the PHP 4 era: allow direct use of COOKIE variables from get post.

For example, in the PHP 4 era, this is allowed by default.

Test. php? A = 123;

Echo $ a; // The value 123.

In the PHP 5 era, only echo $ _ GET ['a'] can be written by default, becauseSecurityCause considerations. This is called automatic global variable, which is included in php. ini. Disabled by default. This configuration item is called register_globals and is enabled by default in some environments. In the Enabled state, you can directly use the variable name to access the variables in the get post cookie. For example, we use SESSION for code and authentication.

If (empty ($ _ SESSION ['username']) die ("No Logon ");

The Automatic Registration of global variables is enabled. You can write it
If (empty ($ username) die ("No Logon ");

However, if someone writes
Test. php? Username = 1; GET variables are also registered as common variables. So the authentication here is passed...

More serious cases
? SQL = select ......

Directly affects our

Mysql_query ($ SQL );

Therefore,Security. Do not enable this function of PHP.

If you create a server for the project. This feature has been enabled. Be careful .. Besides the get post cookie variable. Check the variable with the same name ..

There is a writing method. This can be easily checked.
Foreach ($ _ GET as $ k => $ v ){
If (isset ($ k) and $ k = $ v) unset ($ k );
}

Check all GET variables cyclically and split them by index and value.
Index to form a variable name. If the variable exists beforehand and the value is the same as the current GET value. And then destroy it ..

If we submit test. php? A = 1;
Write the code at the beginning .. At this time, there is no code above. And $ a, if it exists at this time .. That is not what we define .. Destroy it.

This is the so-called never trust the variables submitted by the external, whether submitted by the user or transferred by our own program, for strict checks and judgment. Is necessary. Do not directly use the index name of the predefined variable as the variable name. In addition, try not to use external transfer to directly participate in the operation.

For example, there is a method like this.

Index. php
$ File = $ _ GET ['file'];
Include $ file. ". php ";
?> This writing method is advantageous. You can run several different programs in a program. Index. php? File = news for PHP isInclude "news. php ";Directly use external variables, and the consequence is thatIndex. php? File = http: // my website/hackAs a result, our code becomes include "http: // my website/hack. php ";

Summary:

When using externally transmitted values, you must make certain judgments or formatting.

UploadFileMust be strictly checked.FileType, mandatory when necessaryFileName.

FileUpload must be a POST form, and it must be declared as a data upload. It must be file selectionFile.

FileTemporaryFileFolder,FileThe folder must be accessible.

We need to uploadFileCopy it. Otherwise it will disappear immediately.

Copy the uploadedFile, The move_uploaded_file function should be used to ensureSecurity.

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.