PHP anti-injection configuration and PHP anti-injection Code _php tutorial

Source: Internet
Author: User
Tags file handling phpinfo apache log
There are two types of anti-injection in PHP is SQL anti-injection, and another kind of process like many CMS all submitted variables, there is one can be directly configured php.ini, below I give you introduce.

1. Upload the safe.func.php to the directory of the files to be included

2. To add protection to the page, there are two ways to do so, depending on the situation two, select one:

a). Add code to the page you need to protect

Require_once (' safe.func.php ');
Can do page anti-injection, cross-site
If you want to prevent the whole station, it is in a common file of the website, such as database link file!
Add require_once (' safe.func.php ') to invoke this code

The safe.func.php code is as follows:

The code is as follows Copy Code

* Anti-injection
* "

Operation IP: ". $_server[" REMOTE_ADDR "]."
Operating time: ". Strftime ("%y-%m-%d%h:%m:%s ")."
Action page: ". $_server[" Php_self "]."
Submission method: ". $_server[" Request_method "]."
Submit parameter: ". $StrFiltKey."
Submit data: ". $StrFiltValue);

function Safe_custom_error ($errno, $errstr, $errfile, $errline) {
echo "Error number: [$errno],error on line $errline in $errfile
Die ();

Set_error_handler ("Safe_custom_error", e_error);

function Safe_stop_attack ($k, $v, $method =0) {
$filter = Array (
"'| (and|or). +? (>|<|=|in|like) |/*.+?*/|
"(And|or). {1,6}? (=|>|<|in|like) |/*.+?*/|

$filter = Isset ($filter [$method])? $filter [$method]: $filter [0];

if (Is_array ($v)) {
$v = implode ($v);
if (Preg_match ("/". $filter. "/is", $v) = = 1) {
Exit ("This operation is logged. Please do not continue to operate illegally. ");

if (Isset ($_get)) {
foreach ($_get as $k = $v) safe_stop_attack ($k, $v, 0);
if (Isset ($_post)) {
foreach ($_post as $k = $v) safe_stop_attack ($k, $v, 1);
if (Isset ($_cookie)) {
foreach ($_cookie as $k = $v) safe_stop_attack ($k, $v, 1);

The above is better for anti-SQL injection

The code is as follows Copy Code

/* Filter all get over variables */
foreach ($_get as $get _key=> $get _var)
if (Is_numeric ($get _var)) {
$get [Strtolower ($get _key)] = Get_int ($get _var);
} else {
$get [Strtolower ($get _key)] = Get_str ($get _var);
/* Filter all post-over variables */
foreach ($_post as $post _key=> $post _var)
if (Is_numeric ($post _var))
$post [Strtolower ($post _key)] = Get_int ($post _var);
$post [Strtolower ($post _key)] = Get_str ($post _var);
/* Filter Function */
Integer Filter function
function Get_int ($number)
Return Intval ($number);
string-Type Filter function
function Get_str ($string)
Return addslashes ($string);
return $string;

In addition to anti-injection directly in PHP, we can also configure the php.ini file

。 We will first use any editing tools to open the/usr/local/php/etc/php.ini, if you are installed in another way, the configuration file may not be in this directory.

(1) Open PHP Safe Mode PHP security mode 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 not set, we may not be able to manipulate the files in our server's 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 a hacker is in Telnet 80, it will not be able to see 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:


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:


(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 want to display an error message, be sure to set the level at which the error is displayed, such as displaying only the warning message:

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 sets 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. true techarticle There are two types of anti-injection in PHP is SQL anti-injection, the other is like many CMS process all the variables submitted, there is one can be directly configured php.ini, below I give you ...

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