Hello again, I hvae created a registration page and login page etc. I have done some research and reading on how to restrict certain pages to those not registered or signed in, but I am a little confused on how to make it work. Now I have this code right here:

 <?php

$auth = false; // Assume user is not authenticated

if (isset( $PHP_AUTH_USER ) && isset($PHP_AUTH_PW)) {

// Connect to MySQL

mysql_connect( 'hostname', 'username', 'password' )
    or die ( 'Unable to connect to server.' );

// Select database on MySQL server

mysql_select_db( 'your_db' )
    or die ( 'Unable to select database.' );

// Formulate the query

$sql = "SELECT * FROM users WHERE
        username = '$PHP_AUTH_USER' AND
        password = '$PHP_AUTH_PW'";

// Execute the query and put results in $result

$result = mysql_query( $sql )
    or die ( 'Unable to execute query.' );

// Get number of rows in $result.

$num = mysql_numrows( $result );

if ( $num != 0 ) {

    // A matching row was found - the user is authenticated.

    $auth = true;

}

}

if ( ! $auth ) {

header( 'WWW-Authenticate: Basic realm="Private"' );
header( 'HTTP/1.0 401 Unauthorized' );
echo 'Authorization Required.';
exit;

} else {

echo '<P>You are authorized!</P>';
}

?>

I am just unsure on where to put this. Do I make a seperate file for this or add it to each restricted page or what? I have created a .htpasswd file but have nothing in it. Do I even need it or what. If anyone can offer some insight on this that would be great. Thanks in advance.

    Well, you can do it one of two ways... create a function for it, then call it at the top of each page (suggested), or you continually put this code at the top.

    Here's what I'd do...

    function check_auth(){
            // Make sure the $PHP_AUTH vars are visible inside the function
    	global $PHP_AUTH_USER, $PHP_AUTH_PW;
    
    $auth = false; // Assume user is not authenticated
    
    if (isset( $PHP_AUTH_USER ) && isset($PHP_AUTH_PW)) {
    
        // Connect to MySQL
        mysql_connect( 'hostname', 'username', 'password' )
            or die ( 'Unable to connect to server.' );
    
        // Select database on MySQL server
        mysql_select_db( 'your_db' )
            or die ( 'Unable to select database.' );
    
        // Formulate the query
        $sql = "SELECT * FROM users WHERE
                username = '$PHP_AUTH_USER' AND
                password = '$PHP_AUTH_PW'";
    
        // Execute the query and put results in $result
        $result = mysql_query( $sql )
            or die ( 'Unable to execute query.' );
    
        // Get number of rows in $result.
        $num = mysql_numrows( $result );
    
        if ( $num != 0 ) {
            // A matching row was found - the user is authenticated.
            return TRUE;
        }
    	else{
    		return FALSE;
    	}
    }
    }

    Then, at the top of each page include this file, and call the funciton like so:

    <?Php
    include('user_auth.php');
    if(check_auth() === FALSE){
        header( 'WWW-Authenticate: Basic realm="Private"' );
        header( 'HTTP/1.0 401 Unauthorized' );
        echo 'Authorization Required.';
        exit;
    }
    // otherwise, we can display the page as normal since our if() statement
    // will catch any non-users.
    ?>

    Another option is Sessions or Cookies....

    ~Brett

      Thank you for the reply. That's what I was curious about if I could just do a simple call like you suiggested. So I would create a file named user_auth.php or something along that lines and then on all the pages that are secured add the include statement to that page on each of the secured pages?

      What keeps it from asking for username and password on each page after you have logged in once? Would that where sessions would come in, if so how does all that work? I know that is an extensive question, so if you could just direct me to some readings instead that would be ok.

      -Thanks in Advance.

        Well, with what you were thinking of doing you would get the username/password each time in order to validate their login. And yes, you would just include the file user_auth.php and then run the function.

        Sessions would be your best bet (or cookies if you want, same type of handeling). Basically, you would check to see if they're logged in. So you run your query, and then mySQL either comes back with 1 or 0 rows. Then, if it comes back with 1 row, you set a session var and then check that through each page. If no rows come back, you unset/clear the session var AND destroy the session.

        Then the logout page just destroys the session!!

        For sessions, your code could look like:

        // Generate the authentication & Set the Session!!
        function gen_auth(){
                // Make sure the $PHP_AUTH vars are visible inside the function
            global $PHP_AUTH_USER, $PHP_AUTH_PW;
        
        $auth = false; // Assume user is not authenticated
        
        if (isset( $PHP_AUTH_USER ) && isset($PHP_AUTH_PW)) {
        
            // Connect to MySQL
            mysql_connect( 'hostname', 'username', 'password' )
                or die ( 'Unable to connect to server.' );
        
            // Select database on MySQL server
            mysql_select_db( 'your_db' )
                or die ( 'Unable to select database.' );
        
            // Formulate the query
            $sql = "SELECT * FROM users WHERE
                    username = '$PHP_AUTH_USER' AND
                    password = '$PHP_AUTH_PW'";
        
            // Execute the query and put results in $result
            $result = mysql_query( $sql )
                or die ( 'Unable to execute query.' );
        
            // Get number of rows in $result.
            $num = mysql_numrows( $result );
            $row = mysql_fetch_array($result);
        
            if ( $num != 0 ) {
                session_start();
                // A matching row was found - the user is authenticated.
                $_SESSION['user']['auth'] = 'Authenticated!';
                $_SESSION['user']['user'] = $row['username'];
                $_SESSION['user']['expires'] = time()+(60*60*5); // Expires in 5 hours
            }
            else{
                session_start();
                $_SESSION['user'] = array();
                session_destroy();
            }
        }
        }
        
        function check_auth(){
            if(isset($_SESSION['user']['auth']) && $_SESSION['user']['auth'] == 'Authenticated!'){
                // They are authenticated, let's make sure their session hasn't expired
                if(time() > $_SESSION['user']['expires']){
                    session_destroy();
                    return FALSE;
                }
                else{
                    return TRUE;
                }
            }
        }

        Then, just include this file inside each of your other files, and run either gen_auth() or check_auth().

        <?php
        /*****************************
        ** MUST MUST MUST start each of
        ** your "secured" php pages if
        ** you use sessions!!
        *****************************/
        session_start();
        /****************************/
        include('user_auth.php');
        if(check_auth() === FALSE){
            // Do the header redirect...
        }

        ~Brett

          Thanks, I will give it a shot when I get home from work. Thanks again for the help.

            Write a Reply...