PHP Prevent SQL injection Implementation _php Tutorial

Source: Internet
Author: User
Tags file handling how sql injection works phpinfo apache log
SQL injection because you want to manipulate the database, it is common to look for SQL statement keywords: INSERT, delete, update, select, see if the passed variable parameter is user-controllable, whether it has been handled safely or not.

How SQL injection Works

Constructing a database query is a straightforward process. Typically, it will follow the following ideas. Just to illustrate the problem, we'll assume you have a

Wine database Table "Wines", where one field is "variety" (that is, wine type):

1. Provide a form-allows the user to submit certain content to be searched. Let's assume that the user chooses to search for a wine of 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 Copy Code

$variety = $_post[' variety ');

Therefore, the value of the variable $variety is now:

Lagrein

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

The code is as follows Copy Code

$query = "SELECT * FROM Wines WHERE variety= ' $variety '";

So, the value of the variable $query now looks like this:

The code is as follows Copy Code

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 field variety is "Lagrein".

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

Leads us to complacency. Now, let's re-analyze the query we just built.

1. The fixed part of the query you created ends with a single quotation mark, which you will use to describe the beginning of the value of the variable:

The code is as follows Copy Code

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

2. Use the original invariant parts with values that contain user-submitted variables:

The code is as follows Copy Code

$query. = $variety;

3. Then you use another single quotation mark to connect the result-describes the end of the variable value:

The code is as follows Copy Code

$ query. = "'";

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

The code is as follows Copy Code

SELECT * FROM wines WHERE variety = ' Lagrein '

The success of this construct depends on the user's input. In the example in this article, you are using a single word (or perhaps a group of words) to indicate a type of wine.

Therefore, the query is built without any problems, and the result will be what you expect-a wine list with a wine type of "Lagrein". Is

In, let's imagine that since your users are not entering a simple type of wine type "Lagrein", instead enter the following content (note that the package

including two punctuation marks):

The code is as follows Copy Code

Lagrein ' or 1=1;

Now, you continue to construct your query using the previously pinned sections (here we show only the result values of the $query variable):

The code is as follows Copy Code

SELECT * FROM wines WHERE variety = '

Then, you connect with the value of the variable that contains the user input (in bold):

The code is as follows Copy Code

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

Finally, add the following quotation marks:

The code is as follows Copy Code

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

Condensation above problems we write a function that can prevent.

The code is as follows Copy Code

/**
+----------------------------------------------------------
* Anti-hanging horse, anti-cross-site attack, anti-SQL injection function
+----------------------------------------------------------
* $date parameters passed in, if a variable or an array; $ignore a magic reference to a _magic_quotes variable
+----------------------------------------------------------
*/
function in ($data, $ignore _magic_quotes=false)
{
if (is_string ($data))
{
$data =trim (Htmlspecialchars ($data));//prevent the horse from being hung, cross-site attack
if ($ignore _magic_quotes==true) | | (!GET_MAGIC_QUOTES_GPC ()))
{
$data = Addslashes ($data);//Prevent SQL injection
}
return $data;
}
else if (Is_array ($data))//If the array uses recursive filtering
{
foreach ($data as $key = $value)
{
$data [$key]=in ($value);
}
return $data;
}
Else
{
return $data;
}
}

We can prevent the horse from being hung, cross-site attack and prevent SQL injection waiting when we accept the data above

Here's how to do a security configuration on the server side


(1) Open PHP Safe mode

PHP's security model is a very important embedded security mechanism to control some functions in PHP, such as System (),

At the same time, a lot of file operation functions have permission control, also does not allow the files for some key files, such as/etc/passwd,

But the default php.ini is not open in Safe mode, we turn it on:

Safe_mode = On

(2) User group security

When Safe_mode is turned on, Safe_mode_gid is turned off, and the PHP script is able to access the file, and the same

Users of the group are also able to access the files.

The recommended setting is:

Safe_mode_gid = Off

If we do not set up, we may not be able to operate the files in our server web directory, for example, we need to

When you are working on a file.

(3) Execute Program home directory in Safe mode

If Safe mode is turned on, but you want to execute some programs, you can specify the home directory where you want to execute the program:

The code is as follows Copy Code

Safe_mode_exec_dir = D:/usr/bin

In general, do not need to execute what program, so it is recommended not to execute the System program directory, can point to a directory,

Then copy the program that needs to be executed, such as:

The code is as follows Copy Code

Safe_mode_exec_dir = D:/tmp/cmd

However, I recommend that you do not execute any programs, then you can point to our web directory:

The code is as follows Copy Code

Safe_mode_exec_dir = d:/usr/www

(4) Include files in Safe mode

If you want to include some common files in Safe mode, then modify the options:

The code is as follows Copy Code

Safe_mode_include_dir = d:/usr/www/include/

In fact, the general PHP script contains files are in the program itself has been written, this can be set according to the specific needs.

(5) control the directory that PHP scripts can access

Use the OPEN_BASEDIR option to control the PHP script to access only the specified directory, which avoids the PHP script access

The files that should not be accessed to some extent limit the harm of phpshell, we can generally be set to only access the site directory:

The code is as follows Copy Code

Open_basedir = d:/usr/www

(6) Close danger function

If Safe mode is turned on, then the function prohibition is not necessary, but we consider it to be safe. Like what

We don't want to execute PHP functions that include the system (), or the ability to execute commands, or the ability to view PHP information

Phpinfo () and so on, then we can disable them:

The code is as follows Copy Code

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

If you want to disable the operation of any files and directories, you can close many file operations

The code is as follows Copy Code

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

These are just a few of the most commonly used file handling functions, and you can also combine the above command functions with this function,

will be able to resist most of the Phpshell.

(7) Close the PHP version information in the HTTP header leak

In order to prevent hackers from getting the PHP version of the server information, you can close the information ramp in the HTTP header:

The code is as follows Copy Code

expose_php = Off

For example, when the hacker in Telnet www.12345.com 80, then will not see the PHP information.

(8) Close registered global variables

Variables submitted in PHP, including those that use post or get commits, are automatically registered as global variables and can be accessed directly,

This is very insecure for the server, so we can't register it as a global variable, and turn off the Register global variables option:

The code is as follows Copy Code

Register_globals = Off

Of course, if this is set, then the corresponding variable should be taken in a reasonable way, such as get the variable var of get commit,

Then you need to use $_get[' var ' to get it, this PHP programmer should pay attention to.

(9) Open MAGIC_QUOTES_GPC to prevent SQL injection

SQL injection is a very dangerous problem, small site background was invaded, heavy the entire server fell,

So be sure to be careful. There is a setting in php.ini:

The code is as follows Copy Code

MAGIC_QUOTES_GPC = Off

This is off by default, and if it is turned on, it will automatically convert the query that the user commits to SQL.

It's important to prevent SQL injections, for example, by turning ' switch '. So we recommend setting it to:

The code is as follows Copy Code

MAGIC_QUOTES_GPC = On

(10) Error Message control

In general, PHP is not connected to the database or in other cases there will be a prompt error, the general error message will contain PHP script when

Before the path information or query SQL statements and other information, such information provided to the hacker is not secure, so the general server recommends that you suppress the error prompt:

The code is as follows Copy Code

Display_errors = Off

If you are trying to display an error message, be sure to set the level of display errors, such as displaying only the information above the warning:

The code is as follows Copy Code

error_reporting = e_warning & E_error

Of course, I recommend turning off the error prompt.

(11) Error log

It is recommended to log the error message after closing the display_errors to find out why the server is running:

The code is as follows Copy Code

Log_errors = On

Also set the directory where the error log is stored, suggesting that the root Apache log exists together:

The code is as follows Copy Code

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

Note: The to file must allow Apache users and groups to have write permissions.


MySQL's Down right run

Create a new user such as Mysqlstart

The code is as follows Copy Code

NET user Mysqlstart Fuckmicrosoft/add

net localgroup users Mysqlstart/del

Does not belong to any group

If MySQL is installed in D:mysql, then give Mysqlstart Full control of the permissions

Then set in the system service, MySQL service properties, in the login properties, select this user Mysqlstart and then enter the password, OK.

Restart the MySQL service, and then MySQL runs under low authority.

If the Apache is built under the WinDOS platform, we also need to note that Apache default operation is the system permission,

It's horrible, and it makes you feel uncomfortable. Let's give Apache permission to drop it.

The code is as follows Copy Code

NET user Apache Fuckmicrosoft/add

net localgroup users Apache/del

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

We open the Computer Manager, select the service, point to the properties of the Apache service, we select Log on, choose the This account, we fill in the above established

's account and password,

Restart the Apache service, Ok,apache running under low authority.

In fact, we can also set the permissions of individual folders, so that Apache users can only do what we want it to be able to do, to each directory set up

A single user who can read and write


This article from the program to the database and the final configuration of the Web server has been described, we refer to this article should be safe after a lot of Oh, General injection

There is no way to achieve it.

http://www.bkjia.com/PHPjc/629642.html www.bkjia.com true http://www.bkjia.com/PHPjc/629642.html techarticle SQL injection because you want to manipulate the database, it is common to look for SQL statement keywords: INSERT, delete, update, select, see if the parameters passed by the user can be controlled, have done security ...

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