search
HomeBackend DevelopmentPHP ProblemSummary of methods to prevent SQL injection in PHP

Summary of methods to prevent SQL injection in PHP

Nov 08, 2019 pm 05:09 PM
phpsql injection

Summary of methods to prevent SQL injection in PHP

php method to prevent sql injection

[1. Configuration on the server side]

Safety, PHP code writing is one aspect, and PHP configuration is very critical.

We installed PHP manually. The default configuration file of PHP is in /usr/local/apache2/conf/php.ini. Our most important thing is to configure the content in php.ini. , allowing us to execute php more safely. The security settings in the entire PHP are mainly to prevent attacks from phpshell and SQL Injection. Let’s discuss it slowly. We first 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) Turn on PHP’s safe mode

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

At the same time, many file operation functions are controlled by permissions, and certain key files are not allowed, such as /etc/passwd,

But The default php.ini does not turn on 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 , then the php script can access the file, and users in the same

group can also access the file.

It is recommended to set it to:

safe_mode_gid = off

If you do not set it, we may not be able to operate the files in our server website directory, such as when we need to operate files.

(3) Home directory for executing programs in safe mode

If safe mode is turned on, but you want to execute certain programs, you can specify the program to be executed. Main directory:

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,

and then copy the program that needs to be executed. For example:

safe_mode_exec_dir = D:/tmp/cmd

However, I recommend not to execute any program, 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 public files in safe mode, then modify the options:

safe_mode_include_dir = D:/usr/www/include/

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

(5) Control the directories that PHP scripts can access

Use the open_basedir option to control that PHP scripts can only access specified directories, which can prevent PHP scripts 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

(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 feel that we do not want to execute PHP functions including system() that can execute commands, or

phpinfo() and other functions that can view PHP information, then we can Disable them:

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

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

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

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:

expose_php = Off

For example, when a hacker telnet www.12345.com 80, he will not be able to see the PHP information.

(8) Turn off registration of global variables

Variables submitted in PHP, including variables submitted using POST or GET, will be automatically registered as global Variables can be accessed directly.

This is very unsafe for the server, so we cannot let it be registered as a global variable, so we turn off the registration global variable option:

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 use $_GET['var'] to obtain, PHP programmers should pay attention to this.

(9) Open magic_quotes_gpc to prevent SQL injection

SQL injection is a very dangerous problem. In small cases, the website backend may be invaded, or in serious cases, the entire server may collapse.

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

magic_quotes_gpc = Off

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

for example, convert ' to \' Etc., this plays a significant role in preventing sql injection. Therefore, we recommend setting it to:

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. General error messages The php script will be included when

前的路径信息或者查询的SQL语句等信息,这类信息提供给黑客后,是不安全的,所以一般服务器建议禁止错误提示:

display_errors = Off

如果你却是是要显示错误信息,一定要设置显示错误的级别,比如只显示警告以上的信息:

error_reporting = E_WARNING & E_ERROR

当然,我还是建议关闭错误提示。

(11) 错误日志

建议在关闭display_errors后能够把错误信息记录下来,便于查找服务器运行的原因:

log_errors = On

同时也要设置错误日志存放的目录,建议根apache的日志存在一起:

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

注意:给文件必须允许apache用户的和组具有写的权限。

MYSQL的降权运行

新建立一个用户比如mysqlstart

net user mysqlstart fuckmicrosoft /add
net localgroup users mysqlstart /del

不属于任何组

如果MYSQL装在d:\mysql ,那么,给 mysqlstart 完全控制 的权限

然后在系统服务中设置,MYSQL的服务属性,在登录属性当中,选择此用户 mysqlstart 然后输入密码,确定。

重新启动 MYSQL服务,然后MYSQL就运行在低权限下了。

如果是在windos平台下搭建的apache我们还需要注意一点,apache默认运行是system权限,

这很恐怖,这让人感觉很不爽.那我们就给apache降降权限吧。

net user apache fuckmicrosoft /add
net localgroup users apache /del

ok.我们建立了一个不属于任何组的用户apche。

我们打开计算机管理器,选服务,点apache服务的属性,我们选择log on,选择this account,我们填入上面所建立的账户和密码,

重启apache服务,ok,apache运行在低权限下了。

实际上我们还可以通过设置各个文件夹的权限,来让apache用户只能执行我们想让它能干的事情,给每一个目录建立一个单独能读写的用户。

这也是当前很多虚拟主机提供商的流行配置方法哦,不过这种方法用于防止这里就显的有点大材小用了。 

【二、在PHP代码编写】

防止SQL Injection (sql注射)

SQL 注射应该是目前程序危害最大的了,包括最早从asp到php,基本上都是国内这两年流行的技术,基本原理就是通过对提交变量的不过滤形成注入点然后使恶意用户能够提交一些sql查询语句,导致重要数据被窃取、数据丢失或者损坏,或者被入侵到后台管理。

那么我们既然了解了基本的注射入侵的方式,那么我们如何去防范呢?这个就应该我们从代码去入手了。

我们知道Web上提交数据有两种方式,一种是get、一种是post,那么很多常见的sql注射就是从get方式入手的,而且注射的语句里面一定是包含一些sql语句的,因为没有sql语句,那么如何进行,sql语句有四大句:select 、update、delete、insert,那么我们如果在我们提交的数据中进行过滤是不是能够避免这些问题呢?

于是我们使用正则就构建如下函数:

PHP代码

<?php         
 function inject_check($sql_str)    
 {    
 return eregi(&#39;select|insert|update|delete|&#39;|    
 function verify_id($id=null)    
 {    
 if (!$id) { exit(&#39;没有提交参数!&#39;); } // 是否为空判断    
 elseif (inject_check($id)) { exit(&#39;提交的参数非法!&#39;); } // 注射判断    
 elseif (!is_numeric($id)) { exit(&#39;提交的参数非法!&#39;); } // 数字判断    
 $id = intval($id); // 整型化        
 return $id;    
 }    
 ?>

那么我们就能够进行校验了,于是我们上面的程序代码就变成了下面的:

<?php    
   if (inject_check($_GET[&#39;id&#39;]))    
   {    
   exit(&#39;你提交的数据非法,请检查后重新提交!&#39;);    
   }    
   else    
   {    
   $id = verify_id($_GET[&#39;id&#39;]); // 这里引用了我们的过滤函数,对$id进行过滤    
   echo &#39;提交的数据合法,请继续!&#39;;    
   }    
   ?>

 好,问题到这里似乎都解决了,但是我们有没有考虑过post提交的数据,大批量的数据呢?

比如一些字符可能会对数据库造成危害,比如 ' _ ', ' %',这些字符都有特殊意义,那么我们如果进行控制呢?还有一点,就是当我们的php.ini里面的magic_quotes_gpc = off的时候,那么提交的不符合数据库规则的数据都是不会自动在前面加' '的,那么我们要控制这些问题,于是构建如下函数:

<?php       
  function str_check( $str )    
  {    
  if (!get_magic_quotes_gpc()) // 判断magic_quotes_gpc是否打开    
  {    
  $str = addslashes($str); // 进行过滤    
  }    
  $str = str_replace("_", "\_", $str); // 把 &#39;_&#39;过滤掉    
  $str = str_replace("%", "\%", $str); // 把&#39; % &#39;过滤掉    
        
  return $str;    
  }    
  ?>

最后,再考虑提交一些大批量数据的情况,比如发贴,或者写文章、新闻,我们需要一些函数来帮我们过滤和进行转换,再上面函数的基础上,我们构建如下函数:

<?php     
    function post_check($post)    
    {    
    if (!get_magic_quotes_gpc()) // 判断magic_quotes_gpc是否为打开    
    {    
    $post = addslashes($post); // 进行magic_quotes_gpc没有打开的情况对提交数据的过滤    
    }    
    $post = str_replace("_", "\_", $post); // 把 &#39;_&#39;过滤掉    
    $post = str_replace("%", "\%", $post); // 把&#39; % &#39;过滤掉    
    $post = nl2br($post); // 回车转换    
    $post= htmlspecialchars($post); // html标记转换       
    return $post;    
    }    
?>

注:关于SQL注入,不得不说的是现在大多虚拟主机都会把magic_quotes_gpc选项打开,在这种情况下所有的客户端GET和POST的数据都会自动进行addslashes处理,所以此时对字符串值的SQL注入是不可行的,但要防止对数字值的SQL注入,如用intval()等函数进行处理。但如果你编写的是通用软件,则需要读取服务器的magic_quotes_gpc后进行相应处理。

更多PHP相关知识,请访问PHP中文网

The above is the detailed content of Summary of methods to prevent SQL injection in PHP. For more information, please follow other related articles on the PHP Chinese website!

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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools