How to prevent SQL injection in php

Source: Internet
Author: User
Tags how to prevent sql injection
Methods to prevent SQL injection in php [1. server-side configuration]

Security, PHP code writing is one aspect, and PHP configuration is critical.

We manually install php. the default configuration file of php is in/usr/local/apache2/conf/php. ini, we mainly need to configure php. the content in ini makes it safer to execute php. The security settings in PHP are mainly used to prevent phpshell and SQL Injection attacks. let's take a look at them. Use any editing tool to open/etc/local/apache2/conf/php. ini. if you install it in other ways, the configuration file may not be in this directory.

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

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:

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:

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:

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:

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:

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.

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:

Expose_php = Off

For example, when hackers telnet 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:

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:

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 prevent SQL injection. Therefore, we recommend the following settings:

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:

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:

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:

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:

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

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.

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 account and password created above,

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

In fact, we can also set the permissions for each folder so that apache users can only execute what we want it to do, and create a single read/write user for each directory.

This is also a popular configuration method for many VM providers. However, this method is used to prevent minor usage.

[2. compile code in PHP]

Although many PHP programmers in China are still relying on addslashes to prevent SQL injection, we recommend that you enhance Chinese characters to prevent SQL injection checks. The problem with addslashes is that hackers can use 0xbf27 to replace single quotes, while addslashes only modifies 0xbf27 to 0xbf5c27 to be a valid multi-byte character, where 0xbf5c is still regarded as single quotes, therefore, addslashes cannot be intercepted.
Of course, addslashes is not useless either. it is used for processing single-byte strings and mysql_real_escape_string is used for multi-byte characters.
In addition, the example of get_magic_quotes_gpc in the php Manual is as follows:
If (! Get_magic_quotes_gpc ()){
$ Lastname = addslashes ($ _ POST ['lastname']);
} Else {
$ Lastname = $ _ POST ['lastname'];

If magic_quotes_gpc is enabled, check $ _ POST ['lastname.
Let's talk about the differences between the two functions mysql_real_escape_string and mysql_escape_string:
Mysql_real_escape_string can be used only when (PHP 4> = 4.3.0, PHP 5. Otherwise, only mysql_escape_string can be used. The difference between the two is: mysql_real_escape_string considering the connection
The current character set, but not mysql_escape_string.
* Addslashes () is forcibly added \;
* Mysql_real_escape_string () determines the character set, but it is required for the PHP version;
* Mysql_escape_string does not consider the connected current character set.
Bytes -------------------------------------------------------------------------------------------------
When coding in PHP, if you consider some basic security issues, first of all:
1. initialize your variables
Why? Let's look at the following code:
PHP code
If ($ admin)
Echo 'login successful! ';
Include ('admin. php ');
Echo 'you are not an administrator and cannot manage it! ';
Well, we can see that the code above seems to be running normally, and there is no problem. so what if I add an invalid parameter to the code and submit it? For example, what is our webpage? Admin = 1, haha, you want to know if we are directly an administrator.
Of course, we may not make such a simple mistake, so some very hidden errors may also cause this problem. for example, the phpwind Forum has a vulnerability that allows us to directly obtain administrator privileges, this is because a $ skin variable is not initialized, resulting in a series of problems. So how can we avoid the above problems? First, start with php. ini and set register_global = off in php. ini to avoid it if not all registration variables are global. However, we are not the server administrator and can only improve the code. how can we improve the above code? We rewrite it as follows:
PHP code
$ Admin = 0; // initialize the variable
If ($ _ POST ['admin _ user'] & $ _ POST ['admin _ pass'])
// Determine whether the submitted administrator user name and password are correct.
$ Admin = 1;
$ Admin = 0;
If ($ admin)
Echo 'login successful! ';
Include ('admin. php ');
Echo 'you are not an administrator and cannot manage it! ';
So at this time you submit the Admin = 1 is hard to solve, because we initialized the variable to $ admin = 0 at the beginning, so you cannot obtain administrator permissions through this vulnerability.
2. prevent SQL Injection (SQL Injection)
SQL injection is currently the most harmful to programs, including the earliest from asp to php, which is basically a popular technology in China in the past two years, the basic principle is to create an injection point without filtering the submitted variables and then enable malicious users to submit some SQL query statements, leading to theft, loss, or damage to important data, or be intruded into the background for management.
Now that we understand the basic injection intrusion methods, how can we prevent them? We should start with the code.
We know that there are two ways to submit data on the Web, one is get and the other is post, so many common SQL injections start with get, the injection statement must contain some SQL statements. because there are no SQL statements, there are four SQL statements: select, update, delete, and insert, can we avoid these problems if we filter the submitted data?
Then we construct the following functions using regular expressions:
PHP code
Function inject_check ($ SQL _str)
Return eregi ('select | insert | update | delete | '|
Function verify_id ($ id = null)
If (! $ Id) {exit ('no submission parameter! ');} // Determines whether it is null.
Elseif (inject_check ($ id) {exit ('The submitted parameter is invalid! ');} // Injection judgment
Elseif (! Is_numeric ($ id) {exit ('The submitted parameter is invalid! ');} // Number judgment
$ Id = intval ($ id); // integer
Return $ id;
Then we can verify the code, and the code above becomes the following:
PHP code
If (inject_check ($ _ GET ['id'])
Exit ('The data you submitted is invalid. Please check it and submit it again! ');
$ Id = verify_id ($ _ GET ['id']); // Our filter function is referenced here to filter $ id.
Echo 'The data submitted is valid. please continue! ';
Well, the problem seems to have been solved here, but have we considered the data submitted by post and the large volume of data?
For example, some characters may cause harm to the database, such as '_' and '%'. these characters have special meanings. what if we control them? Another point is our php. when magic_quotes_gpc = off in ini, the submitted data that does not comply with the database rules will not be automatically prefixed with ''. Therefore, we need to control these problems and construct the following functions:
PHP code
Function str_check ($ str)
If (! Get_magic_quotes_gpc () // determines whether magic_quotes_gpc is enabled.
$ Str = addslashes ($ str); // filter
$ Str = str_replace ("_", "\ _", $ str); // filter '_'
$ Str = str_replace ("%", "\ %", $ str); // filter '%'

Return $ str;
Once again, we have avoided the danger of the server being compromised.
Finally, consider submitting large batches of data, such as posting, writing articles, and news. we need some functions to filter and convert the data, we construct the following functions:
PHP code
Function post_check ($ post)
If (! Get_magic_quotes_gpc () // You can check whether magic_quotes_gpc is enabled.
$ Post = addslashes ($ post); // filter submitted data when magic_quotes_gpc is not enabled
$ Post = str_replace ("_", "\ _", $ post); // filter '_'
$ Post = str_replace ("%", "\ %", $ post); // filter '%'
$ Post = nl2br ($ post); // press enter to convert
$ Post = htmlspecialchars ($ post); // html tag conversion
Return $ post;
Well, basically, we have already explained some of the situations here. In fact, I think there are few things I have talked about. at least I have only talked about two things, there is very little content in the overall security. next time, let's talk more about it, including php security configuration and apache Security. This makes our security a whole and the most secure.
Finally, I will tell you the following: 1. initialize your Variables. 2. remember to filter your variables.

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.