Page 221 - Open Soource Technologies 304.indd
P. 221

Unit 9: Web Techniques



            To handle authentication in PHP, check the username and password (the PHP_AUTH_USER   Notes
            and PHP_AUTH_PW elements of $_SERVER) and call header( ) to set the realm and send a
            “401 Unauthorized” response:
            header(‘WWW-Authenticate:  Basic  realm=”Top  Secret  Files”’);  header(“HTTP/1.0  401
            Unauthorized”);
            You can do anything you want to authenticate the username and password; for example, you
            could consult a database, read a file of valid users, or consult a Microsoft domain server. This
            example checks to make sure that the password is the username, reversed:

                          $auth_ok = 0;
            $user = $_SERVER[‘PHP_AUTH_USER’];
            $pass = $_SERVER[‘PHP_AUTH_PW’];

            if (isset($user) && isset($pass) && $user === strrev($pass))
            {
            $auth_ok = 1;
            }
            if (!$auth_ok)

            {
            header(‘WWW-Authenticate: Basic realm=”Top Secret Files”’);
            header(‘HTTP/1.0 401 Unauthorized’);

            }
            Putting this into a document gives something like:
            <?php $auth_ok = 0;
            $user = $_SERVER[‘PHP_AUTH_USER’];
            $pass = $_SERVER[‘PHP_AUTH_PW’];

            if (isset($user) && isset($pass) && $user === strrev($pass))
            {
            $auth_ok = 1;

            }
            if (!$auth_ok)
            {
            header(‘WWW-Authenticate: Basic realm=”Top Secret Files”’);
            header(‘HTTP/1.0 401 Unauthorized’); // anything else printed here is only seen if the client
            hits “Cancel” } ?>
            }<!-- your password-protected document goes here -->

            9.6 Maintaining State


            HTTP is a stateless protocol, which means that once a web server completes a client’s request
            for a web page, the connection between the two goes away. In other words, there is no way for
            a server to recognize that a sequence of requests all originate from the same client.


                                             LOVELY PROFESSIONAL UNIVERSITY                                   215
   216   217   218   219   220   221   222   223   224   225   226