Home Backend Development PHP Tutorial Writing secure scripts with PHP 4.2_PHP Tutorial

Writing secure scripts with PHP 4.2_PHP Tutorial

Jul 21, 2016 pm 04:09 PM
php Safety use of Script

Original work: Kevin Yank Reposted from: www.linuxforum.net (Congratulations on opening this again)

For a long time, one of the biggest selling points of PHP as a server-side scripting language was that it would automatically update the values ​​submitted from the form. Create a global variable. In PHP 4.1, the PHP creators recommended an alternative means of accessing submitted data. In PHP 4.2, they did away with that old practice! As I will explain in this article, the purpose of making such a change is for security reasons. We'll look at new ways PHP handles form submissions and other data, and explain why doing so will make your code more secure.

What’s wrong here?

Look at the following PHP script, which is used to authorize access to a web page when the entered username and password are correct:
// Check username and password
if ($username == 'kevin' and $password == 'secret')
$authorized = true;
?>


Please enter your username and password:



Username:

Password:


< /form>



OK, I believe that about half of the readers will say with disdain, "That's stupid - I wouldn't make such a mistake!" But I guarantee that there are many readers who will think, "Hey, no problem, I will write like this too!" Of course there will be a few people who will be confused by this question ("What is PHP?"). PHP is designed to be a "good and easy" scripting language that beginners can learn to use in a short time; it should also prevent beginners from making the above mistakes.
Going back to the previous question, the problem with the above code is that you can easily gain access without providing the correct username and password. Just add ?authorized=1 at the end of your browser's address bar. Because PHP automatically creates a variable for every submitted value -- whether from a form submission, a URL query string, or a cookie -- this will set $authorized to 1, so an unauthorized user can Security restrictions can be exceeded.
So, how to simply solve this problem? Just set $authorized to false by default at the beginning of the program. This problem no longer exists! $authorized is a variable created entirely in program code; but why should a developer have to worry about every malicious user-submitted variable?

What changes have been made in PHP 4.2?

In PHP 4.2, the register_globals option in newly installed PHP is turned off by default, so the EGPCS value (EGPCS is the abbreviation of Environment, Get, Post, Cookies, Server - This is the source of external variables in PHP full scope) will not be created as global variables. Of course, this option can also be turned on manually, but PHP developers recommend that you turn it off. To implement their intent, you need to use other methods to obtain these values.
Starting from PHP 4.1, the EGPCS value can be obtained from a specified set of arrays:
$_ENV -- Contains system environment variables
$_GET -- Contains variables in the query string, and submission method Variables in the GET form
$_POST -- Contains variables in the form submitted as POST
$_COOKIE -- Contains all cookie variables
$_SERVER -- Contains server variables, such as HTTP_USER_AGENT
$_REQUEST -- Contains the entire contents of $_GET, $_POST and $_COOKIE
$_SESSION -- Contains all registered session variables
Before PHP 4.1, when the developer turned off the register_globals option (this was also considered (as a way to improve PHP performance), you have to use nasty names like $HTTP_GET_VARS to get these variables. Not only are these new variable names shorter, but they also have other advantages.
First, let’s rewrite the code mentioned above in PHP 4.2 (which means turning off the register_globals option):
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];

// Check username and password
if ($username == 'kevin' and $password == 'secret')
$authorized = true;
?>


Please enter your username and password:



Username :

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 username and password to be submitted by the user, we get these values ​​from the $_REQUEST array. Using this array allows the user to freely choose the delivery method: through a URL query string (for example, allowing users to automatically enter their credentials when creating a bookmark), through a form submission, or through a cookie. If you want to restrict certificate submission to only via forms (more precisely, via HTTP POST requests), you can use the $_POST array:
$username = $_POST['username'];
$password = $_POST['password'];
Except for "introducing" these two variables, there is no change in the program code. Simply turning off the register_globals option forces developers to better understand which data is coming from external (untrusted) sources.
Please note that there is a small problem here: the default error_reporting setting in PHP is still E_ALL & ~E_NOTICE, so if the two values ​​​​of "username" and "password" have not been submitted, trying to get the value from the $_REQUEST array or $_POST Obtaining these two values ​​​​in the array does not incur any error messages. If your PHP program needs strict error checking, you will also need to add some code to check these variables first.

But does this mean more input?

Yes, in simple programs like the above, using PHP 4.2 often increases the amount of typing. But let’s look on the bright side – your program is safer after all!
But seriously, the designers of PHP did not completely ignore your pain. These new arrays have a special feature that no other PHP variable has, they are completely global variables. How does this help you? Let's first expand on our example.
In order to enable multiple pages in the site to use username/password arguments, we write our user authentication program into an include file (protectme.php):
function authorize_user($authuser, $authpass)
{
$username = $_POST['username'];
$password = $_POST['password'];
// Check username and password
if ($username != $authuser or $password != $authpass):
?>

Very simple and clear, right? Now it’s time to test your eyesight and experience – what’s 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 turned on, 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, unlike other languages ​​with similar syntax, variables outside functions are not automatically available in functions. You need to add a line as explained above to specify where they come from. global scope.
In PHP 4.0, when register_globals is turned off to provide security, you can use the $HTTP_POST_VARS array to obtain the values ​​submitted by your form, but you still need to import this array from the global scope:
function authorize_user($ authuser, $authpass)
{
global $HTTP_POST_VARS;
$username = $HTTP_POST_VARS['username'];
$password = $HTTP_POST_VARS['password'];
But in PHP In versions 4.1 and later, the special $_POST variable (and the others mentioned above) can be used in all scopes. This is why there is no need to declare the $_POST variable as a global variable in the function:
function authorize_user($authuser, $authpass)
{
$username = $_POST['username'];
$password = $_POST['password'];

What impact does this have on the session?

The introduction of the special $_SESSION array actually helps simplify the session code. Instead of declaring session variables as global variables and then keeping track of which variables are registered, you can now simply reference all your session variables from $_SESSION['varname'].
Now let’s look at another example of user authentication. This time, we use sessions to indicate that a user who continues to stay on your site has been authenticated. First, let’s take a look at the PHP 4.0 version (enable register_globals):
session_start();
if ($username == 'kevin' and $password == 'secret')
{
$authorized = true;
session_register('authorized');
}
?>





Similar to the initial program, this program also has security vulnerabilities. Adding ?authorized=1 at the end of the URL can bypass security measures and directly access the page content. Developers can treat $authorized as a session variable and ignore that the same variable can easily be set via user input.
After we add our special array (PHP 4.1) and turn off register_globals (PHP 4.2), our program will look like this:
session_start();
if ($username == 'kevin' and $password == 'secret')
$_SESSION['authorized'] = true;
?>





Is it simpler? You no longer need to register a normal variable as a session variable, you just need to set the session variable directly (in the $_SESSION array) and use it in the same way. Programs are shorter and there is less confusion about what variables are session variables!

Summary

In this article, I explained the underlying reasons for the changes to the PHP scripting language. In PHP 4.1, a special set of data was added to access external data. These arrays can be called in any scope, which makes access to external data more convenient. In PHP 4.2, register_globals is turned off by default to encourage the use of these arrays to prevent inexperienced developers from writing unsafe PHP code.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314671.htmlTechArticleOriginal work: Kevin Yank Reprinted from: www.linuxforum.net (Congratulations on opening this again) For a long time, PHP One of the biggest selling points of a server-side scripting language is that values ​​submitted from forms are automatically generated...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles