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

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

Dependency injection provides object dependencies through external injection in PHP, improving the maintainability and flexibility of the code. Its implementation methods include: 1. Constructor injection, 2. Set value injection, 3. Interface injection. Using dependency injection can decouple, improve testability and flexibility, but attention should be paid to the possibility of increasing complexity and performance overhead.

Implementing dependency injection (DI) in PHP can be done by manual injection or using DI containers. 1) Manual injection passes dependencies through constructors, such as the UserService class injecting Logger. 2) Use DI containers to automatically manage dependencies, such as the Container class to manage Logger and UserService. Implementing DI can improve code flexibility and testability, but you need to pay attention to traps such as overinjection and service locator anti-mode.

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
