But doesn't that mean more typing?
Yes, in simple scripts like the one above, the new way of doing things in PHP 4.2 does often require more typing. But hey, look on the bright side -- you could start charging by the keystroke! Seriously though, the makers of PHP are not entirely insensitive to your pain (I have a half brother who suffers from repetitive stress injuries). A special feature of these new arrays is that, unlike all other PHP variables, they are totally global. How does this help you? Let's extend our example a little to see. To allow for multiple pages on the site to require a username/password combination to be viewed, we'll move our authorization code into an include file (protectme.php ) as follows: /#pc#/<?php /* protectme.php */ function authorize_user($authuser, $authpass) { $username = $_POST['username']; $password = $_POST['password']; // Check the username and password if ($username != $authuser or $password != $authpass): ?> <!-- Unauthorized users are prompted for their credentials --> <p>Please enter your username and password:</p> <form action="<?=$_SERVER['PHP_SELF']?>" method="POST"> <p>Username: <input type="text" name="username" /><br /> Password: <input type="password" name="password" /><br /> <input type="submit" /></p> </form> <?php exit(); endif; } ?>/#epc#/ Now, our protected page looks like this: <?php require('protectme.php'); authorize_user('kevin','secret'); ?> <!-- Super-Secret HTML content goes here -->
Nice and simple, right? Now here's a challenge for the especially eagle-eyed and experienced -- what's missing from the authorize_user function? What's missing is the declaration of $_POST inside the function to bring it in from the global scope! In PHP 4.0, with register_globals turned on, you'd have had add a line of code to get access to the $username and $password variables inside the function: /#pc#/ function authorize_user($authuser, $authpass) { global $username, $password; .../#epc#/ In PHP, unlike in other languages with similar syntax, variables outside a function are not automatically available inside the function. You need to specifically bring them in with the global line demonstrated above. With register_globals turned off in PHP 4.0 to improve security, you would use the $HTTP_POST_VARS array to obtain the values submitted from your form, but you would still have had to import that array from the global scope: /#pc#/ function authorize_user($authuser, $authpass) { global $HTTP_POST_VARS; $username = $HTTP_POST_VARS['username']; $password = $HTTP_POST_VARS['password'];/#epc#/ But in PHP 4.1 or later, the special $_POST variable (and the rest of the special variables listed in the previous section) are always available in all scopes. This is why the $_POST variable didn't need to be declared global at the top of the function: function authorize_user($authuser, $authpass) { $username = $_POST['username']; $password = $_POST['password'];
|