PHP prevents SQL injection methods, Phpsql injection
"One, server-side Configuration"
Security, PHP code writing is on the one hand, PHP configuration is very critical.
We PHP hand-installed, PHP default configuration file in/usr/local/apache2/conf/php.ini, we mostly want to configure the content in PHP.ini, let us execute PHP can be more secure. The security settings throughout PHP are primarily designed to prevent Phpshell and SQL injection attacks, and we'll explore them slowly. We will first use any editing tools to open the/etc/local/apache2/conf/php.ini, if you are installed in another way, the configuration file may not be in this directory.
(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:
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:
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:
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:
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:
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:
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
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:
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:
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:
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.
For example, "switch to \" And so on, which is important to prevent SQL injection. So we recommend setting it to:
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:
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:
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:
Log_errors = On
Also set the directory where the error log is stored, suggesting that the root Apache log exists together:
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
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.
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 this account, we fill in the accounts and passwords established above,
Restart the Apache service, Ok,apache running under low authority.
In fact, we can also set individual folder permissions, so that Apache users can only do what we want it to do, to each directory to create a separate read and write users.
This is also a popular configuration method for many current web hosting providers, but this method is used to prevent a bit of overkill here.
"Two, write in PHP code"
Although many PHP programmers in the country still rely on addslashes to prevent SQL injection, it is recommended to strengthen Chinese to prevent SQL injection check. The problem with addslashes is that hackers can use 0xbf27 instead of single quotes, and addslashes just modifies 0xbf27 to 0xbf5c27 as a valid multibyte character, where 0xbf5c is still considered a single quote, So addslashes can't intercept successfully.
Of course addslashes is not useless, it is used for single-byte string processing, multibyte characters or mysql_real_escape_string bar.
Another example of GET_MAGIC_QUOTES_GPC in the PHP manual:
if (!GET_MAGIC_QUOTES_GPC ()) {
$lastname = addslashes ($_post[' LastName ');
} else {
$lastname = $_post[' LastName ');
}
It is best to check the $_post[' LastName ' If the MAGIC_QUOTES_GPC is already open.
Again, the difference between the 2 functions of mysql_real_escape_string and mysql_escape_string:
Mysql_real_escape_string must be used in cases (PHP 4 >= 4.3.0, PHP 5). Otherwise only with mysql_escape_string, the difference between the two is: Mysql_real_escape_string considering the connected
The current character set, while Mysql_escape_string is not considered.
To summarize:
* Addslashes () is forcibly added \;
* Mysql_real_escape_string ()Will determine the character set, but the PHP version is required;
* Mysql_escape_string does not consider the current character set of the connection.
-------------------------------------------------------------------------------------------------
In PHP code, if you consider some of the more basic security issues, first of all:
1. Initialize your variables
Why do you say that? Let's look at the following code:
PHP code
if ($admin)
{
Echo ' landed successfully! ';
Include (' admin.php ');
}
Else
{
Echo ' You are not an administrator and cannot be managed! ';
}
?>
OK, we see the above code seems to be able to run normally, no problem, then join me to submit an illegal parameter in the past, then the effect will be? For example, this page of ours is http://daybook.diandian.com/login.php, then we submit: Http://daybook.diandian.com/login.php?admin=1, hehe, you want some, We are directly the administrator, direct management.
Of course, we may not make such a simple mistake, then some very secret errors may also lead to this problem, such as the Phpwind forum has a loophole, resulting in the ability to directly get administrator privileges, because there is a $skin variable is not initialized, resulting in a series of problems later. So how do we avoid the above problem? First of all, from the php.ini, php.ini inside the Register_global =off, is not all the registered variables for the global, then you can avoid. However, we are not a server administrator, only improved from the code, then how can we improve the above code? We rewrite the following:
PHP code
$admin = 0; Initialize variables
if ($_post[' Admin_user ') && $_post[' Admin_pass '])
{
Determine if the submitted administrator user name and password are correct for the corresponding processing code
// ...
$admin = 1;
}
Else
{
$admin = 0;
}
if ($admin)
{
Echo ' landed successfully! ';
Include (' admin.php ');
}
Else
{
Echo ' You are not an administrator and cannot be managed! ';
}
?>
Then it's not good for you to submit http://daybook.diandian.com/login.php?admin=1 again, because we initialized the variable to $admin = 0 at the outset, so you can't get administrator privileges through this vulnerability.
2. Preventing SQL injection (SQL injection)
SQL injection should be the most harmful to the current program, including the earliest from the ASP to PHP, is basically the domestic two years of popular technology, the basic principle is through the non-filtering of the commit variable to form an injection point and then enable malicious users to submit some SQL query statements, resulting in important data theft, data loss or corruption, Or be hacked into the background management.
So now that we know the basic way of injecting intrusion, how do we prevent it? This should be our code to start with.
We know that there are two ways to submit data on the Web, one is get, one is post, so many common SQL injections start with GET, and the injected statement must contain some SQL statements, because there is no SQL statement, then how to proceed, The SQL statement has four main sentences: Select, update, delete, insert, so we can avoid these problems if we filter on the data we submit.
So we use the regular to build the following function:
PHP code
function Inject_check ($sql _str)
{
Return eregi (' select|insert|update|delete| ' |
function verify_id ($id =null)
{
if (! $id) {exit (' No arguments are submitted! '); }//Is null-judged
ElseIf (Inject_check ($id)) {exit (' argument submitted is illegal! '); }//Injection judgment
ElseIf (!is_numeric ($id)) {exit (' argument submitted is illegal! '); }//Digital judgment
$id = Intval ($id); The whole type of
return $id;
}
?>
Well, then we will be able to verify, so our above program code becomes the following:
PHP code
if (Inject_check ($_get[' id '))
{
Exit (' The data you submitted is illegal, please check and resubmit! ');
}
Else
{
$id = verify_id ($_get[' id "); Our filter function is referenced here to filter the $id.
Echo ' submitted data is valid, please continue! ';
}
?>
OK, the problem seems to have been solved here, but we have not considered the post-submitted data, large quantities of data?
For example, some characters may be harmful to the database, such as ' _ ', '% ', these characters have special meaning, then if we control it? Another point is that when our php.ini inside the MAGIC_QUOTES_GPC = off, then the data submitted by the database does not conform to the rules are not automatically added to the front, then we have to control these problems, and then build the following function:
PHP code
function Str_check ($STR)
{
if (!GET_MAGIC_QUOTES_GPC ())//Determine if MAGIC_QUOTES_GPC is open
{
$str = Addslashes ($STR); To filter
}
$str = Str_replace ("_", "\_", $str); Filter out the ' _ '
$str = str_replace ("%", "\%", $str); Filter out the '% '
return $str;
}
?>
Once again, we avoided the danger of the server being overrun.
Finally, consider submitting some large quantities of data, such as posts, or writing articles, news, we need some functions to help us filter and transform, and then on the basis of the above function, we construct the following function:
PHP code
function Post_check ($post)
{
if (!GET_MAGIC_QUOTES_GPC ())//Determine if MAGIC_QUOTES_GPC is open
{
$post = Addslashes ($post); To filter the submission data without opening the MAGIC_QUOTES_GPC
}
$post = Str_replace ("_", "\_", $post); Filter out the ' _ '
$post = str_replace ("%", "\%", $post);//filter out '% '
$post = NL2BR ($post);//Return conversion
$post = Htmlspecialchars ($post);//html tag conversion
return $post;
}
?>
Oh, basic to here, we have said some of the situation, in fact, I feel that I speak a few things, at least I only said two aspects, and then the whole security is very little content, consider the next time to speak more, including PHP security Configuration, Apache security, etc., so that our security is a whole , making it the safest.
Finally, I'm telling you the above: 1. Initialize your variable 2. Be sure to filter your variables
What's the best way to prevent SQL injection in PHP?
If the user enters a query that is inserted directly into an SQL statement, the application is vulnerable to SQL injection, such as the following example: $unsafe _variable = $_post[' user_input '); mysql_query ("INSERT into table (column) VALUES (')." $unsafe _variable. "')"); This is because the user can enter similar value "); DROP table tables; -To make the query: use a pre-defined statement and a parameterized query. SQL statements with any parameters will be sent to the database server and parsed! It is impossible for an attacker to inject SQL into a malicious way! There are two basic options for achieving this: 1. Using PDO (PHP Data Objects): $stmt = $pdo->prepare (' SELECT * FROM employees WHERE name =: Name '); $stmt->execute (Array (': Name ' = $name)); foreach ($stmt as $row) {//do something with $row}2. Using mysqli: $stmt = $dbConnection->prepare (' SELECT * FROM Employees WHERE name =? '); $stmt->bind_param (' s ', $name); $stmt->execute (); $result = $stmt->get_result (); while ($row = $result->fetch_assoc ()) {//does something with $row}pdo (PHP data Object) Note When using PDO to access the MySQL database The true pre-defined statement is not used by default! To solve this problem, you must disable the prepared statements for emulation. Examples of creating a connection using PDO are as follows: $dbConnection = new PDO (' Mysql:dbname=dbtest;host=127.0.0.1;charset=utf8 ', ' user ', ' pass '); $dbConnection->setattribute (Pdo::attr_emulate_prepares, false); $dbConnection->setattribute (Pdo::attr_errmode, pdo::errmode_exception); In the above example, the error mode Errmode is not strictly necessary, but it is recommended to add it. This method script does not stop when there is a fatal error in running an error. and give developers the opportunity to catch any errors (when throwing pdoexception exceptions). SetAttribute () That line is mandatory, it tells PDO to disable the emulation of the pre-defined statements, using the real pre-defined statements. This ensures that statements and values are not parsed by PHP before being sent to the MySQL database server (the attacker has no opportunity to inject malicious SQL). Of course you can set the character set parameters in the constructor options, paying special attention to the ' old ' PHP version (5.3.6) that ignores character set parameters in the DSN. The most important thing here is that the parameter value is combined with a precompiled statement instead of a SQL string. SQL injection works by spoofing the creation of SQL scripts including malicious string hair ... Remaining full text >>
How PHP prevents SQL injection
Well, that's the answer my teacher gave me.
Answer: Filter Some common database operation keywords,
Select, insert,update,delete,and,*, or filter content by system function addslashes
Register_globals=off in PHP configuration file, set to off state. (The function will register the global variable off); If the value of the receiving POST form is used $_post[' user '), the $user receives the value if set to On
When writing SQL statements, try not to omit the Kohiki number (the tab above) and the single quotation mark
Improve the database naming skills, for some important fields according to the characteristics of the program named, making it difficult to guess
Encapsulation of common methods to avoid direct burst SQL statements
Open PHP Safe Mode safe_mode=on
Open MAGIC_QUOTES_GPC to prevent SQL injection, the default is to turn off, automatically after the user submits the SQL query statement to convert the "'" into "\"
Control error message output, turn off error message prompt, write error message to system log
Pretreatment with Mysqli or PDO
http://www.bkjia.com/PHPjc/882620.html www.bkjia.com true http://www.bkjia.com/PHPjc/882620.html techarticle PHP to prevent SQL injection method, Phpsql injection "one, server-side Configuration" Security, PHP code is written on the one hand, PHP configuration is very critical. Our PHP hand-installed, ...