As PHP programmers, especially novices, they always know too little about the dangers of the Internet. They are often helpless against external intrusions. They have no idea how hackers invade, submit intrusions, upload vulnerabilities, and SQL Injections, cross-scripting attacks, and more. As the most basic precaution, you need to pay attention to your external submissions and make the first security mechanism to deal with the firewall.
Rule 1: Never trust external data or input
The first thing you must realize about web application security is that external data should not be trusted. External data includes any data that is not entered directly by the programmer in the PHP code. Any data from any other source (such as GET variables, form POST, databases, configuration files, session variables, or cookies) cannot be trusted until steps are taken to ensure security.
For example, the following data elements can be considered safe because they are set in PHP.
Listing 1. Safe and flawless code
Copy the code The code is as follows:
$myUsername = 'tmyer ';
$arrayarrayUsers = array('tmyer', 'tom', 'tommy');
define("GREETING", 'Hello there' . $myUsername);
?>
However, the following data elements are flawed.
Listing 2. Unsafe, flawed code
Copy the code The code is as follows:
$myUsername = $_POST['username']; //tainted!
$arrayarrayUsers = array($myUsername, 'tom', 'tommy'); //tainted!
define("GREETING ", 'hello there' . $myUsername); //tainted!
?>
Why is the first variable $myUsername defective? Because it comes directly from the form POST. Users can enter any string into this input field, including malicious commands to clean files or run previously uploaded files. You might ask, "Can't you avoid this danger by using a client-side (Javascript) form validation script that only accepts the letters A-Z?" Yes, this is always a beneficial step, but as we'll see later , anyone can download any form to their machine, modify it, and resubmit whatever they need.
The solution is simple: the sanitization code must be run on $_POST['username']. If you don't do this, you could pollute these objects any other time you use $myUsername (such as in an array or constant). A simple way to sanitize user input is to use regular expressions to process it. In this example, only letters are expected to be accepted. It might also be a good idea to limit the string to a specific number of characters, or require all letters to be lowercase.
Listing 3. Making user input safe
Copy the code The code is as follows:
$myUsername = cleanInput($_POST['username']); //clean!
$arrayarrayUsers = array($myUsername, 'tom', 'tommy'); //clean!
define( "GREETING", 'hello there' . $myUsername); //clean!
function cleanInput($input){ $clean = strtolower($input);
$clean = preg_replace(“/[^a-z] /", "", $clean);
$clean = substr($clean,0,12);return $clean;
}
?>
Rule 2: Disable PHP settings that make security difficult to implement Now that you can’t trust user input, you should also know that you shouldn’t trust the way PHP is configured on the machine. For example, make sure register_globals is disabled. If register_globals is enabled, it's possible to do careless things like use a $variable to replace a GET or POST string with the same name. By disabling this setting, PHP forces you to reference the correct variables in the correct namespace. To use variables from a form POST, $_POST['variable'] should be quoted. This way you won't mistake this particular variable for a cookie, session, or GET variable.
Rule 3: If you can’t understand it, you can’t protect it Some developers use strange syntax, or organize statements very compactly to form a short but meaningful Obscure code. This approach may be efficient, but if you don't understand what the code is doing, you can't decide how to protect it. For example, which of the following two pieces of code do you like?
Listing 4. Making code easy to protect
Copy the code The code is as follows:
//obfuscated code
$input = (isset($_POST['username']) ? $_POST['username']:”);
//unobfuscated code
$input = ”;
if (isset($_POST['username'])){
$input = $_POST['username'];
}else{
$input = ”;
}
In the second, clearer code snippet, it’s easy to see that $input is flawed and needs to be cleaned up before it can be safely processed.
Rule 4: “Defense in depth” is the new magic weapon This tutorial will use examples to illustrate how to protect online forms, while using the PHP code that processes the form. necessary measures. Likewise, even if you use PHP regex to ensure that GET variables are entirely numeric, you can still take steps to ensure that SQL queries use escaped user input. Defense in depth is not just a good idea, it ensures that you don't get into serious trouble. Now that the basic rules have been discussed, let's look at the first threat: SQL injection attacks.
◆Prevent SQL injection attacks
In a SQL injection attack, the user adds information to the database query by manipulating the form or GET query string. For example, assume you have a simple login database. Each record in this database has a username field and a password field. Build a login form to allow users to log in.
Copy code The code is as follows:
This form accepts a username and password entered by the user and submits the user input to a file called verify.php. In this file, PHP handles the data from the login form as follows:
Listing 5. Unsafe PHP form handling code
Copy code The code is as follows:
$okay = 0;
$username = $_POST['user'];
$pw = $_POST[ 'pw'];
$sql = "select count(*) as ctr from users where username='
".$username."' and password='". $pw."' limit 1″;
$result = MySQL_query($sql);
while ($data = mysql_fetch_object($result)){
if ($data->ctr == 1){
//they' re okay to enter The application!
$okay = 1;
}
}
if ($okay){
$_SESSION['loginokay'] = true;
header( "index.php");
}else{
header("login.php");
}
?>
This code does not look like Question, right? Hundreds (maybe even thousands) of PHP/MySQL sites around the world use code like this. What's wrong with it? Well, remember "user input cannot be trusted". No information from the user is escaped here, thus leaving the application vulnerable. Specifically, any type of SQL injection attack may occur. For example, if the user enters foo as the username and ' or '1′='1 as the password, the following string is actually passed to PHP, which then passes the query to MySQL:
Copy code The code is as follows:
$sql = "select count(*) as ctr from users where username=
' foo' and password=” or '1′='1′ limit 1″;
?>
This query always returns a count of 1, so PHP will allow access. By injecting some malicious SQL at the end of the password string, the hacker can impersonate the legitimate user. The solution to this problem is to use PHP's built-in mysql_real_escape_string() function as a wrapper around any user input. The characters in are escaped, making it impossible to pass special characters such as apostrophes in the string and allowing MySQL to operate according to the special characters. Listing 7 shows the code with escape processing. Definition processing code
Copy code
The code is as follows:
$okay = 0;
$username = $_POST['user'];
$pw = $_POST['pw'];
$ sql = "select count(*) as ctr from users where username='".mysql_real_
_string($username)."' and password='". mysql_real_escape_string($pw)."'
limit 1" ;
$result = mysql_query($sql);
while ($data = mysql_fetch_object($result)){
if ($data->ctr == 1){ //they're okay to enter the
application!
$okay = 1;
}
}
if ($okay){
$_SESSION['loginokay'] = true;
header ("index.php");
}
else{
header("login.php");
}
?>
Using mysql_real_escape_string () acts as a wrapper around user input, thus avoiding any malicious SQL injection in user input. If a user attempts to pass a malformed password via SQL injection, the following query will be passed to the database:
Copy code The code is as follows:
select count(*) as ctr from users where username='foo' and password=
'' or '1'='1′ limit 1″
http://www.bkjia.com/PHPjc/322437.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322437.htmlTechArticleAs PHP programmers, especially novices, they always know too little about the dangers of the Internet and external intrusions. There are many times when they are helpless. They have no idea how hackers get in...