Php prevention of SQL injection implementation method _ PHP Tutorial

Source: Internet
Author: User
Tags how sql injection works
Php prevents SQL injection. Because SQL injection is required to operate on the database, it generally looks for SQL statement keywords: insert, delete, update, and select to check whether the passed variable parameters are controllable, whether SQL injection has been performed securely. Because database operations are required, the keywords of SQL statements such as insert, delete, update, and select are generally queried to check whether the passed variable parameters are controllable and whether security processing has been performed.

How SQL injection works

Constructing a database query is a very direct process. Typically, it follows the following steps. We will assume that you have

Wine database table "wines", with a field "variety" (that is, the wine type ):

1. provide a form that allows users to submit certain content to be searched. Let's assume that you select a wine with the search type "lagrein.

2. retrieve the user's search term and save it-by assigning it to a variable as follows:

The code is as follows:

$ Variety = $ _ POST ['variety'];

Therefore, the value of $ variety is:

Lagrein

3. Then, use this variable to construct a database query in the WHERE clause:

The code is as follows:

$ Query = "SELECT * FROM wines WHERE variety = '$ variety '";

Therefore, the value of the variable $ query is as follows:

The code is as follows:

SELECT * FROM wines WHERE variety = 'lagrein'

4. submit the query to the MySQL server.

5. MySQL returns all records in the wines table-where the value of the variety field is "lagrein ".

So far, this should be a very easy process that you are familiar. Unfortunately, sometimes we are familiar with and comfortable with the process.

This leads to complacency. Now, let's analyze the query we just created.

1. the fixed part of the query you created ends with a single quotation mark. you will use it to describe the start of the variable value:

The code is as follows:

$ Query = "SELECT * FROM wines WHERE variety = '";

2. use the original fixed part and the value that contains the variable submitted by the user:

The code is as follows:

$ Query. = $ variety;

3. then, you use another single quotation mark to connect this result-the end of the variable value:

The code is as follows:

$ Query. = "'";

Therefore, the value of $ query is as follows:

The code is as follows:

SELECT * FROM wines WHERE variety = 'lagrein'

The successful construction depends on the user input. In this example, you are using a single word (or a group of words) to indicate a type of wine.

Therefore, there is no problem in the construction of this query, and the result will also be what you expect-a wine list with a wine type of "lagrein. Now

As you can imagine, since your user does not enter a simple type of wine of the "lagrein" type, you enter the following content (note package

Including two punctuation marks ):

The code is as follows:

Lagrein 'or 1 = 1;

Now, you continue to use the fixed section above to construct your query (here, we only display the result value of the $ query variable ):

The code is as follows:

SELECT * FROM wines WHERE variety ='

Then, you connect to the value of the variable containing the user input (shown in bold here ):

The code is as follows:

SELECT * FROM wines WHERE variety = 'lagrein' or 1 = 1;

Finally, add the following quotation marks:

The code is as follows:

SELECT * FROM wines WHERE variety = 'lagrein' or 1 = 1 ;'

We can write a function to avoid the above problems.

The code is as follows:

/**
+ ----------------------------------------------------------
* Anti-Trojan, cross-site attack, and SQL injection functions
+ ----------------------------------------------------------
* $ Date indicates the input parameter, which is a variable or array. magic reference of $ ignore_magic_quotes variable
+ ----------------------------------------------------------
*/
Function in ($ data, $ ignore_magic_quotes = false)
{
If (is_string ($ data ))
{
$ Data = trim (htmlspecialchars ($ data); // prevents Trojans and cross-site attacks
If ($ ignore_magic_quotes = true) | (! Get_magic_quotes_gpc ()))
{
$ Data = addslashes ($ data); // prevents SQL injection
}
Return $ data;
}
Else if (is_array ($ data) // use recursive filtering for an array
{
Foreach ($ data as $ key => $ value)
{
$ Data [$ key] = in ($ value );
}
Return $ data;
}
Else
{
Return $ data;
}
}

When we accept data above, we can prevent Trojans and cross-site attacks, and prevent SQL injection waiting.

The following describes how to configure security on the server.


(1) enable the php Security mode

The security mode of php is a very important embedded security mechanism that can control some php functions, such as system (),

At the same time, many File operation functions are subject to permission control, and files of some key files are not allowed, such as/etc/passwd,

However, the default php. ini mode does not enable the security mode. open it:

Safe_mode = on

(2) User Group Security

When safe_mode is enabled and safe_mode_gid is disabled, the php script can access the file and

Group users can also access files.

Recommended settings:

Safe_mode_gid = off

If you do not set it, we may not be able to operate the files under the website directory of our server. for example, we need

During file operations.

(3) main directory for executing programs in safe mode

If security mode is enabled, but you want to execute some programs, you can specify the main directory of the program to be executed:

The code is as follows:

Safe_mode_exec_dir = D:/usr/bin

Generally, you do not need to execute any program. Therefore, we recommend that you do not execute the System program directory, which can point to a directory,

Then copy the program to be executed, for example:

The code is as follows:

Safe_mode_exec_dir = D:/tmp/cmd

However, I recommend that you do not execute any program, so you can point to our webpage Directory:

The code is as follows:

Safe_mode_exec_dir = D:/usr/www

(4) file inclusion in security mode

If you want to include some public files in safe mode, modify the following options:

The code is as follows:

Safe_mode_include_dir = D:/usr/www/include/

In fact, the files contained in the php script are all written in the program itself, which can be set as needed.

(5) control directories accessible by php scripts

You can use the open_basedir option to control the PHP script to access only the specified directory, so as to avoid PHP script access.

Files that should not be accessed limit the harm of phpshell to a certain extent. we can generally set to only access the website directory:

The code is as follows:

Open_basedir = D:/usr/www

(6) disable dangerous functions

If the security mode is enabled, the function is not required, but we should consider it for security. For example,

We do not want to execute a php function that includes system () and so on that can execute commands, or can view php information.

Phpinfo () and other functions, we can disable them:

The code is as follows:

Disable_functions = system, passthru, exec, shell_exec, popen, phpinfo

If you want to disable operations on any files and directories, you can disable many file operations.

The code is as follows:

Disable_functions = chdir, chroot, dir, getcwd, opendir, readdir, scandir, fopen, unlink, delete, copy, mkdir,

Rmdir, rename, file, file_get_contents, fputs, fwrite, chgrp, chmod, chown

The above only lists some file processing functions that are not commonly used. you can also combine the preceding command functions with this function,

You can resist most phpshells.

(7) disable PHP version information leakage in the http header

To prevent hackers from obtaining information about the php version on the server, we can disable this information in the http header:

The code is as follows:

Expose_php = Off

For example, when hackers telnet www.12345.com 80, they will not be able to see the PHP information.

(8) disable registration of global variables

Variables submitted in PHP, including those submitted using POST or GET, are automatically registered as global variables and can be directly accessed,

This is very insecure for the server, so we can disable the register global variable option if we cannot register it as a global variable:

The code is as follows:

Register_globals = Off

Of course, if this is set, a reasonable way should be used to obtain the corresponding variable, such as getting the variable var submitted by GET,

You need to use $ _ GET ['var'] to obtain it. This php programmer should pay attention to it.

(9) enable magic_quotes_gpc to prevent SQL injection.

SQL injection is a very dangerous problem. in small cases, the website background is intruded, while in heavy cases, the entire server is compromised,

So be careful. Php. ini has a setting:

The code is as follows:

Magic_quotes_gpc = Off

This is disabled by default. if it is enabled, it will automatically convert the SQL query submitted by the user,

For example, convert 'to' to ', which plays a major role in preventing SQL injection. Therefore, we recommend the following settings:

The code is as follows:

Magic_quotes_gpc = On

(10) error message control

In general, php prompts an error when it is not connected to the database or in other cases. the common error message will contain the php script when

The preceding path information or the queried SQL statement information is not safe after the information is provided to the hacker. Therefore, it is recommended that the server disable the error prompt:

The code is as follows:

Display_errors = Off

If you want to display the error information, you must set the display error level. for example, only the warning information is displayed:

The code is as follows:

Error_reporting = E_WARNING & E_ERROR

Of course, we recommend that you disable the error message.

(11) error log

We recommend that you record the error information after you disable display_errors to find out the reason for running the server:

The code is as follows:

Log_errors = On

At the same time, you must set the directory where error logs are stored. it is recommended that the logs of the root apache exist together:

The code is as follows:

Error_log = D:/usr/local/apache2/logs/php_error.log

Note: You must grant write permissions to apache users and groups.


MYSQL downgrading operation

Create a user, such as mysqlstart

The code is as follows:

Net user mysqlstart fuckmicrosoft/add

Net localgroup users mysqlstart/del

Does not belong to any group

If MYSQL is installed in d: mysql, grant full control of MYSQL start.

Then, set the MYSQL service attribute in the system service. in the logon attribute, select this user mysqlstart and enter the password to confirm.

Restart the MYSQL service and MYSQL runs under low permissions.

If you build apache on the windos platform, note that apache runs with the system permission by default,

This is terrible, and it makes people feel uncomfortable. let's drop apache permissions.

The code is as follows:

Net user apache fuckmicrosoft/add

Net localgroup users apache/del

OK. We have created a user apche that does not belong to any group.

Open the computer manager, select a service, click the apache service attribute, select log on, select this account, and fill in the created

Account and password,

Restart the apache service. OK. apache runs under low permissions.

In fact, we can also set permissions for each folder so that apache users can only execute what we want it to do and create

A single user capable of reading and writing


This article describes the configuration from the program to the database and the final WEB server. after you refer to this article, we should be much safer.

There is no way to achieve this.

...

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.