Use PHP to write secure script code

Source: Internet
Author: User
For a long time, as one of the biggest selling points of the server-side scripting language, PHP automatically creates a global variable for the value submitted from the form. In PHP4.1, PHP producers recommended an alternative way to access and submit data.

For a long time, as one of the biggest selling points of the server-side scripting language, PHP automatically creates a global variable for the value submitted from the form. In PHP 4.1, PHP producers recommended an alternative way to access and submit data.

In PHP 4.2, they canceled the old practice! As I will explain in this article, the purpose of such a change is to ensure security. We will study new PHP practices when processing form submissions and other data, and explain why this improves code security.

What are the errors?

Take a look at the following PHP script, which is used to authorize access to a Web page when the user name and password entered are correct:
The Code is as follows:
// Check the user name and password
If ($ username = 'kevin 'and $ password = 'secret ')
$ Authorized = true;
?>


Please enter your username and password:







Okay, I believe about half of the readers will say, "It's too stupid-I won't make such a mistake !" But I promise many readers will think, "Hi, no problem. I will write it like that too !" Of course, a few people will be confused about this problem ("What is PHP ?"). PHP is designed as a "good and easy" scripting language that beginners can learn to use in a short period of time. It should also be able to avoid beginners from making the above errors.
Back to the problem above, the problem in the code above is that you can easily obtain access power without providing the correct user name and password. Only Add at the end of your browser's address bar? Authorized = 1. Because PHP automatically creates a variable for each submitted value-whether it is from a submitted form, URL query string, or a cookie-this will set $ authorized to 1, such an unauthorized user can break through the security restrictions.
So how can we solve this problem simply? You only need to set $ authorized to false by default at the beginning of the program. This problem does not exist! $ Authorized is a variable completely created in the program code. But why do developers worry about the variable submitted by every malicious user?

What changes have PHP 4.2 made?

In PHP 4.2, the register_globals option in the newly installed PHP is disabled by default, therefore, EGPCS are not created as global variables (EGPCS are short for Environment, Get, Post, Cookies, and Server-this is the full range of external variable sources in PHP. Of course, this option can also be enabled manually, but PHP developers recommend that you disable it. To fulfill their intentions, you need to use other methods to obtain these values.
Starting from PHP 4.1, the EGPCS value can be obtained from the specified array:
$ _ ENV -- contains system environment variables
$ _ GET -- contains the variables in the query string and the variables in the form submitted with the GET method.
$ _ POST -- contains the variables in the form whose submission method is POST.
$ _ COOKIE -- contains all cookie variables
$ _ SERVER -- contains SERVER variables, such as HTTP_USER_AGENT
$ _ REQUEST -- contains all content of $ _ GET, $ _ POST, and $ _ COOKIE
$ _ SESSION -- contains all registered session Variables
Before PHP 4.1, when developers disable the register_globals option (this is also considered to improve PHP performance, you must use annoying names such as $ HTTP_GET_VARS to obtain these variables. These new variable names are not only short, but also have other advantages.
First, let's rewrite the Code mentioned above in PHP 4.2 (that is, disable the register_globals option:
The Code is as follows:
$ Username = $ _ REQUEST ['username'];
$ Password = $ _ REQUEST ['Password'];

// Check the user name and password
If ($ username = 'kevin 'and $ password = 'secret ')
$ Authorized = true;
?>


Please enter your username and password:







As you can see, all I need to do is add the following two lines at the beginning of the Code:
$ Username = $ _ REQUEST ['username'];
$ Password = $ _ REQUEST ['Password'];
Because we want the user name and password to be submitted by the user, we get these values from the $ _ REQUEST array. You can use this array to select the transmission mode: query strings through URLs (for example, allow users to automatically enter their certificates when creating bookmarks), submit a form, or use a cookie. If you want to limit that certificates can only be submitted through forms (more specifically, http post requests), you can use the $ _ POST array:
$ Username = $ _ POST ['username'];
$ Password = $ _ POST ['Password'];
Except for the "introduced" variables, the program code has not changed. Simply disabling the register_globals option allows developers to learn more about which data comes from external (untrusted) resources.
Note that the default error_reporting setting in PHP is still E_ALL &~ E_NOTICE. Therefore, if the values "username" and "password" are not submitted, attempting to obtain these two values from the $ _ REQUEST array or the $ _ POST array does not cause any error message. If your PHP program requires strict error checks in the morning, you need to add some code to check these variables first.

But does this mean more input?

Yes. In simple programs like above, using PHP 4.2 often increases input. However, let's look at the bright side-your program is safer after all!
But seriously, PHP designers do not fully ignore your pain. In these new arrays, there is a special feature that PHP variables do not possess. They are full global variables. How can this help you? Let's expand our example first.
To enable the user name/password argument for multiple pages on the site, we write our user authentication program to an include file (protectme. php:
The Code is as follows:
Function authorize_user ($ authuser, $ authpass)
{
$ Username = $ _ POST ['username'];
$ Password = $ _ POST ['Password'];
// Check the user name and password
If ($ username! = $ Authuser or $ password! = $ Authpass ):
?>

Please enter your username and password:



Exit ();
Endif;
}
?>

Now, the page we just created looks like this:
The Code is as follows:
Require ('protectme. php ');
Authorize_user ('kevin ', 'secret ');
?>


Very simple, clear, right? Now is the time to test your eyesight and experience-what is missing in the authorize_user function?
$ _ POST is not declared as a global variable in the function! In php 4.0, when register_globals is enabled, you need to add a line of code to get the $ username and $ password variables in the function:
Function authorize_user ($ authuser, $ authpass)
{
Global $ username, $ password;
...
In PHP, different from other languages with similar syntax, variables outside the function cannot be automatically obtained in the function, you need to add a row as described above to specify its global range.
In PHP 4.0, When you disable register_globals to provide security, you can use the $ HTTP_POST_VARS array to obtain the value submitted by your form, but you still need to import the array from the global scope:
Function authorize_user ($ authuser, $ authpass)
{
Global $ HTTP_POST_VARS;
$ Username = $ HTTP_POST_VARS ['username'];
$ Password = $ HTTP_POST_VARS ['Password'];
However, in PHP 4.1 and later versions, special $ _ POST variables (and other variables mentioned above) can be used in all scopes. This is why you do not need to declare the $ _ POST variable in the function as a global variable:
Function authorize_user ($ authuser, $ authpass)
{
$ Username = $ _ POST ['username'];
$ Password = $ _ POST ['Password'];

What is the impact on the session?

The introduction of special $ _ SESSION array actually helps simplify the session code. You do not need to declare the session variable as a global variable, and then pay attention to which variables are registered, now you can reference all your SESSION variables from $ _ session ['varname.
Now let's take a look at another user authentication example. This time, we use sessions to indicate that a user who continues to stay on your website has been authenticated by the user. First, let's take a look at PHP 4.0 (enabling register_globals ):
The Code is as follows:
Session_start ();
If ($ username = 'kevin 'and $ password = 'secret ')
{
$ Authorized = true;
Session_register ('authorized ');
}
?>






Like the initial program, this program also has a security vulnerability. What should I add at the end of the URL? Authorized = 1 can bypass security measures to directly access the page content. Developers can regard $ authorized as a session variable while ignoring the fact that they can easily set the same variable through user input.
When we add our special array (PHP 4.1) and disable register_globals (PHP 4.2), our program will be like this:
The Code is as follows:
Session_start ();
If ($ username = 'kevin 'and $ password = 'secret ')
$ _ SESSION ['authorized'] = true;
?>






Is it simpler? You no longer need to register a common variable as a session variable. You only need to directly set the session variable (in the $ _ SESSION array) and use it in the same way. The program has become shorter, and it will not cause confusion about what variables are session variables!

Summary

In this article, I explained the underlying reasons for the change in the PHP scripting language. In PHP 4.1, a set of special data is added to access external data. These arrays can be called within any range, making it easier to access external data. In PHP 4.2, register_globals is disabled by default to encourage the use of these arrays to prevent inexperienced developers from coding insecure PHP code.

I have never tried. How can I know?

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.