Code security and SQL Injection prevention in PHP

Source: Internet
Author: User
Tags sql injection prevention

/*************************
* Author: heiyeluren
* QQ: 37035600
* Email: heiyeluren@163.com
*************************/

How to Implement php code security and ensure the security of programs and servers is a very important issue when various hackers are rampant. I casually read the information about php security, not many, at least less than asp. There is not much technical content here. I just talked about it in a simple way. (The following operations are based on PHP + MySQL + Apache, unless otherwise specified)

Let's talk about security first. Let's take a look at two articles:
Http://www.xfocus.net/articles/200107/227.html
Http://www.xfocus.net/articles/200107/228.html

The above article focuses on the security of PHP, which basically gives a comprehensive introduction to some PHP security issues.

When coding in PHP, if you consider some basic security issues, first of all:
1. initialize your Variables

Why? Let's look at the following code:
If ($ admin)
{
Echo login successful !;
Include (admin. php );
}
Else
{
Echo you are not an administrator and cannot manage it !;
}

Well, we can see that the code above seems to be running normally, and there is no problem. So what if I add an invalid parameter to the code and submit it? For example, if our webpage is http://www.traget.com/login.php, can we submit it at: http://www.target.com/login.php? Admin = 1, haha, you want to know if we are directly an administrator.
Of course, we may not make such a simple mistake, so some very hidden errors may also cause this problem. For example, the phpwind 1.3.6 forum that has been exposed recently has a vulnerability, as a result, you can directly obtain the Administrator permission because a $ skin variable is not initialized, resulting in a series of problems.

So how can we avoid the above problems? First, start with php. ini and set register_global = off in php. ini to avoid it if not all registration variables are global. However, we are not the server administrator and can only improve the Code. How can we improve the above Code? We rewrite it as follows:
$ Admin = 0; // initialize the variable
If ($ _ POST [admin_user] & $ _ POST [admin_pass])
{
// Determine whether the submitted administrator user name and password are correct.
//...
$ Admin = 1;
}
Else
{
$ Admin = 0;
}

If ($ admin)
{
Echo login successful !;
Include (admin. php );
}
Else
{
Echo you are not an administrator and cannot manage it !;
}

So at this time you submit the http://www.target.com/login.php? Admin = 1 is hard to solve, because we initialized the variable to $ admin = 0 at the beginning, so you cannot obtain administrator permissions through this vulnerability.


2. Prevent SQL Injection (SQL Injection)

SQL injection is currently the most harmful to programs, including the earliest from asp to php, which is basically a popular technology in China in the past two years, the basic principle is to create an injection point without filtering the submitted variables and then enable malicious users to submit some SQL query statements, leading to theft, loss, or damage to important data, or be intruded into the background for management.
I will not talk about the basic principles. Let's take a look at the following two articles to understand:
Http://www.4ngel.net/article/36.htm
Http://www.4ngel.net/article/30.htm

Now that we understand the basic injection intrusion methods, how can we prevent them? We should start with the code.

We know that there are two ways to submit data on the Web, one is get and the other is post, so many common SQL injections start with get, in addition, the injection statement must contain some SQL statements. Because there are no SQL statements, there are four SQL statements:
Select, update, delete, and insert. Can we avoid these problems if we filter the data we submit?
Then we construct the following functions using regular expressions:

/*
Function Name: inject_check ()
Function function: checks whether submitted values contain SQL Injection characters to prevent injection and protect server security.
Parameter: $ SQL _str: Submitted variable
Return Value: Return detection result, true or false
Function Author: heiyeluren
*/
Function inject_check ($ SQL _str)
{
Return eregi (select | insert | update | delete |/* | ../|./| union | into | load_file | outfile, $ SQL _str); // Filter
}

In our function, select, insert, update, delete, union, into, load_file, outfile /*,. /,.. /, and so on. If all the dangerous parameter strings are filtered out, the submitted parameters can be controlled. The program can be constructed as follows:

<? Php
If (inject_check ($ _ GET [id])
{
Exit (the data you submitted is invalid. Check the data and submit it again !);
}
Else
{
$ Id = $ _ GET [id];
The data submitted by echo is valid. Please continue !;
}
?>
Suppose we submit the URL to: http://www.target.com/a.php? Id = 1, then the prompt is displayed:
"The submitted data is valid. Please continue! "
If we submit http://www.target.com/a.php? Id = 1 select * from tb_name
The following message is displayed: "The data you submitted is invalid. Check the data and submit it again! "

Then we met our requirements.

However, the problem has not been resolved, if we submit a http://www.target.com/a.php? Id = 1 asdfasdfasdf. we comply with the above rules, but it does not meet the requirements, so we may want, let's build another function to check:

/*
Function Name: verify_id ()
Function: checks whether the submitted ID class value is valid.
Parameter: $ id: Submitted ID value
Return Value: return the ID after processing.
Function Author: heiyeluren
*/
Function verify_id ($ id = null)
{
If (! $ Id) {exit (No parameter submitted !); } // Determines if it is null
Elseif (inject_check ($ id) {exit (the submitted parameter is invalid !); } // Injection judgment
Elseif (! Is_numeric ($ id) {exit (the submitted parameter is invalid !); } // Digital judgment
$ Id = intval ($ id); // integer
 
Return $ id;
}

Then we can verify the code, and the code above becomes the following:

<? Php
If (inject_check ($ _ GET [id])
{
Exit (the data you submitted is invalid. Check the data and submit it again !);
}
Else
{
$ Id = verify_id ($ _ GET [id]); // Our filter function is referenced here to filter $ id.
The data submitted by echo is valid. Please continue !;
}
?>

Well, the problem seems to have been solved here, but have we considered the data submitted by post and the large volume of data?
For example, some characters may cause harm to the database, such as _, %, which all have special meanings. What if we want to control them? Another point is our php. when magic_quotes_gpc = off in ini, the submitted data that does not comply with the database rules will not be automatically added before. Therefore, we need to control these problems and construct the following functions:

/*
Function Name: str_check ()
Function: Filter submitted strings.
Parameter: $ var: string to be processed
Return Value: returns the filtered string.
Function Author: heiyeluren
*/
Function str_check ($ str)
{
If (! Get_magic_quotes_gpc () // determines whether magic_quotes_gpc is enabled.
{
$ Str = addslashes ($ str); // Filter
}
$ Str = str_replace ("_", "\ _", $ str); // filter _ out
$ Str = str_replace ("%", "\ %", $ str); // filter % Out

Return $ str;
}

Okay, we once again avoided the danger of the server being compromised.

Finally, consider submitting large batches of data, such as posting, writing articles, and news. We need some functions to filter and convert the data, we construct the following functions:

/*
Function Name: post_check ()
Function: process submitted edits.
Parameter: $ post: content to be submitted
Return Value: $ post: The filtered content is returned.
Function Author: heiyeluren
*/
Function post_check ($ post)
{
If (! Get_magic_quotes_gpc () // you can check whether magic_quotes_gpc is enabled.
{
$ Post = addslashes ($ post); // magi

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