search
HomeBackend DevelopmentPHP TutorialHow to prevent sql injection in php_PHP tutorial
How to prevent sql injection in php_PHP tutorialJul 13, 2016 pm 05:10 PM
insphpsqlgenerallyKeywordsaccomplishoperatedatabasemethodFindinjectionstatementprevent

Because SQL injection requires operating the database, it generally looks for SQL statement keywords: insert, delete, update, select, and checks whether the passed variable parameters are user-controllable and whether security processing has been done

How SQL injection works

Constructing a database query is a very straightforward process. Typically, it will be implemented along the following lines. Just for illustrative purposes, we'll assume you have one

There is a wine database table "wines", one of which is "variety" (i.e. wine type):

1. Provide a form - allow users to submit something to search for. Let's assume that the user chooses to search for wine of type "lagrein".

2. Retrieve the user's search term and save it - by assigning it to a variable like this:

The code is as follows Copy code
 代码如下 复制代码

$variety = $_POST['variety'];

$variety = $_POST['variety'];

Therefore, the value of variable $variety is now:

lagrein

3. Then, use the variable to construct a database query in the WHERE clause:
 代码如下 复制代码

$query = “SELECT * FROM wines WHERE variety=’$variety’”;

The code is as follows Copy code

$query = “SELECT * FROM wines WHERE variety=’$variety’”;

 代码如下 复制代码

SELECT * FROM wines WHERE variety=’lagrein’

So, the value of 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 - among them, the value of field variety is "lagrein".

By now, this should be a familiar and easy process. Unfortunately, sometimes the processes we are familiar with and comfortable with are easy

Leading us to complacency. Now, let's reanalyze the query we just constructed.
 代码如下 复制代码

$query = ” SELECT * FROM wines WHERE variety = ‘”;

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

The code is as follows Copy code
 代码如下 复制代码

$query .= $variety;

$query = ” SELECT * FROM wines WHERE variety = ‘”;

2. Use the original fixed part and contain the value of the user-submitted variable:
 代码如下 复制代码

$ query .= “‘”;

The code is as follows Copy code
$query .= $variety;
3. You then use another single quote to concatenate this result - describing the end of the variable value:
The code is as follows Copy code
$ query .= “‘”;

So, the value of $query is as follows:

The code is as follows Copy code
 代码如下 复制代码

SELECT * FROM wines WHERE variety = ‘lagrein’

SELECT * FROM wines WHERE variety = ‘lagrein’

The success of this construct relies on user input. In this example, you are using a single word (or possibly a group of words) to specify a type of wine.

So the query is constructed without any issues and the result is what you would expect - a list of wines with the wine type "lagrein". Now

Now, let’s imagine that instead of entering a simple wine type of type “lagrein”, your user enters the following (note the package

(including two punctuation marks):
 代码如下 复制代码

lagrein’ or 1=1;

The code is as follows Copy code

lagrein’ or 1=1;

 代码如下 复制代码

SELECT * FROM wines WHERE variety = ‘

Now, you continue to construct your query using the previously fixed parts (here, we only show the result value of the $query variable):

The code is as follows Copy code
SELECT * FROM wines WHERE variety = ‘
 代码如下 复制代码

SELECT * FROM wines WHERE variety = ‘lagrein’ or 1=1;

You then connect to it using the value of the variable containing the user input (shown here in bold):

The code is as follows Copy code
 代码如下 复制代码

SELECT * FROM wines WHERE variety = ‘lagrein’ or 1=1;’

SELECT * FROM wines WHERE variety = ‘lagrein’ or 1=1;
Finally, add the lower quotes above and below:
The code is as follows Copy code
SELECT * FROM wines WHERE variety = ‘lagrein’ or 1=1;’

We can prevent the above problems by writing a function.

The code is as follows Copy code
 代码如下 复制代码

/**
+----------------------------------------------------------
* 防挂马、防跨站攻击、防sql注入函数
+----------------------------------------------------------
*$date 传入的参数,要是个变量或者数组;$ignore_magic_quotes变量的魔术引用
+----------------------------------------------------------
*/
function in($data,$ignore_magic_quotes=false)
{
 if(is_string($data))
 {
  $data=trim(htmlspecialchars($data));//防止被挂马,跨站攻击
  if(($ignore_magic_quotes==true)||(!get_magic_quotes_gpc()))
  {
     $data = addslashes($data);//防止sql注入
  }
  return  $data;
 }
 else if(is_array($data))//如果是数组采用递归过滤
 {
  foreach($data as $key=>$value)
  {
    $data[$key]=in($value);
  }
  return $data;
 }
 else
 {
  return $data;
 } 
}

/**

+------------------------------------------------- ----------

* Anti-horse, anti-cross-site attack, anti-sql injection function

+------------------------------------------------- ---------- *The parameter passed in by $date must be a variable or array; the magic reference of the $ignore_magic_quotes variable +------------------------------------------------- ----------

*/

function in($data,$ignore_magic_quotes=false)
{

if(is_string($data))

{

$data=trim(htmlspecialchars($data));//Prevent being hacked and cross-site attacks

if(($ignore_magic_quotes==true)||(!get_magic_quotes_gpc()))

{

$data = addslashes($data);//Prevent sql injection

}

return $data;

}

else if(is_array($data))//If it is an array, use recursive filtering

{

foreach($data as $key=>$value)

{

$data[$key]=in($value);

}

Return $data;

}

else

{

Return $data;

}

}

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

The following will introduce security configuration on the server side
 代码如下 复制代码

safe_mode_exec_dir = D:/usr/bin

(1) Turn on the safe mode of php

 代码如下 复制代码

safe_mode_exec_dir = D:/tmp/cmd

php’s safe mode is a very important built-in security mechanism that can control some functions in php, such as system(),

At the same time, the permissions of many file operation functions are controlled, and certain key files, such as /etc/passwd, are not allowed.
 代码如下 复制代码

safe_mode_exec_dir = D:/usr/www

But the default php.ini does not open safe mode, let’s open it: safe_mode = on (2) User group security When safe_mode is turned on, safe_mode_gid is turned off, then the php script can access the file, and it is the same Users in the group can also access the file. Recommended settings are: safe_mode_gid = off If we don’t set it up, we may not be able to operate the files in our server website directory. For example, we need to When operating on files. (3) The main directory of the execution program in safe mode If safe mode is turned on but you want to execute certain programs, you can specify the home directory of the program to be executed:
The code is as follows Copy code
safe_mode_exec_dir = D:/usr/bin
Generally, there is no need to execute any program, so it is recommended not to execute the system program directory. You 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 not to execute any program, 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 certain public files in safe mode, then change the options:

The code is as follows Copy code
 代码如下 复制代码

safe_mode_include_dir = D:/usr/www/include/

safe_mode_include_dir = D:/usr/www/include/

In fact, generally the files included in php scripts have been written in the program itself. This can be set according to specific needs.

(5) Control the directories that php scripts can access

Use the open_basedir option to control the PHP script to only access the specified directory, which can prevent the PHP script from accessing

Files that should not be accessed limit the harm of phpshell to a certain extent. We can generally set it to only access the website directory:
 代码如下 复制代码

open_basedir = D:/usr/www

The code is as follows Copy code

open_basedir = D:/usr/www

(6) Turn off dangerous functions

If safe mode is turned on, function prohibition is not necessary, but we still consider it for safety. For example,

We don’t think we want to execute PHP functions including system() that can execute commands, or that can view PHP information

 代码如下 复制代码

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

phpinfo() and other functions, then we can ban them:

The code is as follows Copy code
disable_functions = system,passthru,exec,shell_exec,popen,phpinfo
 代码如下 复制代码

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

If you want to prohibit any file and directory operations, 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

The above only lists some of the commonly used file processing functions. You can also combine the above execution command function with this function,

 代码如下 复制代码

expose_php = Off

It can resist most phpshells.

(7) Close the leakage of PHP version information in the http header

In order to prevent hackers from obtaining the PHP version information in the server, we can turn off the information in the http header:

The code is as follows Copy code
expose_php = Off

For example, when a hacker telnet www.12345.com 80, he will not be able to see PHP information.
 代码如下 复制代码

register_globals = Off

(8) Close registration of global variables Variables submitted in PHP, including those submitted using POST or GET, will be automatically registered as global variables and can be accessed directly, This is very unsafe for the server, so we can’t let it be registered as a global variable, so we turn off the register global variable option:
The code is as follows Copy code
register_globals = Off

Of course, if this is set, then reasonable methods must be used to obtain the corresponding variables, such as obtaining the variable var submitted by GET,

Then you need to use $_GET['var'] to get it. PHP programmers should pay attention to this.

(9) Turn on magic_quotes_gpc to prevent SQL injection

SQL injection is a very dangerous problem. In the smallest case, the website backend may be invaded, or in the worst case, the entire server may collapse.

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

The code is as follows Copy code
 代码如下 复制代码

magic_quotes_gpc = Off

magic_quotes_gpc = Off

This is turned off by default. If it is turned on, it will automatically convert the SQL query submitted by the user,

For example, convert ' to ', etc., which plays a significant role in preventing sql injection. So we recommend setting it to:
 代码如下 复制代码

magic_quotes_gpc = On

The code is as follows Copy code

magic_quotes_gpc = On

(10) Error message control

Generally, PHP will prompt an error when it is not connected to the database or under other circumstances. Generally, the error message will contain a PHP script when

The path information before
 代码如下 复制代码

display_errors = Off

or the query SQL statement and other information are unsafe if provided to hackers, so it is generally recommended that servers disable error prompts:

The code is as follows Copy code
display_errors = Off
 代码如下 复制代码

error_reporting = E_WARNING & E_ERROR

If you want to display an error message, be sure to set the level of display error, for example, only display information above warning:

The code is as follows Copy code

error_reporting = E_WARNING & E_ERROR

Of course, I still recommend turning off error prompts.

 代码如下 复制代码

log_errors = On

(11) Error log

It is recommended to record the error information after turning off display_errors, so as to find the reason why the server is running:
 代码如下 复制代码

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

The code is as follows Copy code
log_errors = On
At the same time, you must also set the directory where the error log is stored. It is recommended that the root apache log be stored together:
The code is as follows Copy code
error_log = D:/usr/local/apache2/logs/php_error.log

Note: The file must be given to allow the apache user and group to have write permissions.


MYSQL’s privilege-reduced operation

Create a new user such as mysqlstart

The code is as follows
 代码如下 复制代码

net user mysqlstart fuckmicrosoft /add

net localgroup users mysqlstart /del

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 permissions
 代码如下 复制代码

net user apache fuckmicrosoft /add

net localgroup users apache /del

Then set the MYSQL service properties in the system service. In the login properties, select this user mysqlstart and enter the password and confirm.

Restart the MYSQL service, and then MYSQL will run with low privileges.

If apache is built on a windos platform, we need to pay attention to one thing. Apache runs with system permissions by default,

This is scary, this makes people feel very uncomfortable. Then let’s lower the permissions of apache.

ok. We created a user apche that does not belong to any group.
The code is as follows

Copy code

net user apache fuckmicrosoft /add


net localgroup users apache /del

We open the computer manager, select services, click on the properties of the apache service, we select log on, select this account, we fill in the values ​​created above

’s account and password, Restart the apache service, ok, apache is running with low permissions. In fact, we can also set the permissions of each folder so that the apache user can only perform what we want it to do, and create a for each directory. A single user who can read and write This article covers everything from the program to the database and the final WEB server configuration. You should be much safer after referring to this article. General injection There is no way to achieve it.
http://www.bkjia.com/PHPjc/629642.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629642.htmlTechArticleSQL injection requires operating the database, so it generally looks for SQL statement keywords: insert, delete, update, select, Check whether the passed variable parameters are user-controllable and whether safety measures have been taken...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),