I've put most of my energy into coding security these days because a project with a high degree of security needs to be started. Also learned about some of the security vulnerabilities in PHP coding. such as XSS attacks and SQL injection. Due to my qualifications is still shallow, can not try to write the attack class code, this article only records I in recent days by learning PHP security coding knowledge to prevent and reduce the risk of being attacked.
1. About XSS attacks
First, let's look at a PHP code first:
< form Action = "
" > < input type = " submit " Name = " Submit " Value = " submit " />
The purpose is to submit to the current page. When we enter the http://localhost/xss/index.php. The page was submitted normally. That's the result we want.
But the browser also http://localhost/xss/index.php?a=1 when the time comes. That's not what we want. When we enter Http://localhost/xss/index.php/%3E%22%3E%3Cscript%3Ealert%28%27xss%27%29%3C/script%3E in the browser
Let's see what happens. Yes, the browser pops up the XSS prompt box. This indicates that the site is in danger of being attacked by XSS.
So how do we solve this problem, please look at the following code:
< form Action = "
" > < input type = " submit " Name = " Submit " Value = " submit " />
Now commit the above malicious code again, so that we can avoid being attacked.
The Htmlspecialchars function converts some pre-defined characters to HTML entities.
2. About SQL injection
Let's take a look at the following example (this example just plays an illustrative role and has no practical effect):
$name = $_get [ ' username ' ]; Mysql_query ("Select * from users WHERE name = ' { $name } '");
When we enter http://localhost/xss/index.php?username=confusing in the browser, we normally enter the SQL SELECT statement. This is the result we want.
But when we entered in the browser: http://localhost/xss/index.php?username=confusing ';D elete from users;
This SQL statement becomes:
SELECT * from users WHERE name = ' confusing ' ; DELETE from users;
What a horrible thing. This statement removes the Users table.
So how do we prevent such a thing from happening?
1). Verify the input
Look at the following code snippet:
if (GET_MAGIC_QUOTES_GPC ()) {
$name = Stripslashes ($name);
$name = mysql_real_escape_string ($_get[' username '); ); Mysql_query ("Select * from users WHERE name = ' { $name } '");
Isn't that safer?
There are some good PHP libraries, like the one I mentioned in the previous article CType. Are some of the tools that verify good validation data. As long as we do not bear its annoyance to carefully examine the user input data can minimize the chance of attack.
Today only write so much, I am also in the study. If found more will be updated directly in the department.