Hard-Coded Authentication
The simplest way to restrict resource access is by hard-coding the username and password
directly into the script. Listing 14-2 offers an example of how to accomplish this.
Listing 14-2. Authenticating Against a Hard-Coded Login Pair
if (($_SERVER['PHP_AUTH_USER'] != 'specialuser') ||
($_SERVER['PHP_AUTH_PW'] != 'secretpassword')) {
header('WWW-Authenticate: Basic Realm="Secret Stash"');
header('HTTP/1.0 401 Unauthorized');
print('You must provide the proper credentials!');
exit;
}
In this example, if $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] are
equal to specialuser and secretpassword, respectively, the code block will not execute,
and anything ensuing that block will execute. Otherwise, the user is prompted for
the username and password until either the proper information is provided or a 401
Unauthorized message is displayed due to multiple authentication failures.
Although authentication against hard-coded values is very quick and easy to
configure, it has several drawbacks. Foremost, all users requiring access to that resource
must use the same authentication pair. In most real-world situations, each user must
be uniquely identified so that user-specific preferences or resources can be provided.
Second, changing the username or password can be done only by entering the code
and making the manual adjustment. The next two methodologies remove these issues.
Pages:
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448