Free2Code
 
Time: 2008-11-21, 10:16am
Protecting My PHP Pages.
Subject: Need Help Protecting My PHP Pages.  ·  Posted: 2008-02-16, 08:29pm
Rank: ? (1)
Member #: 29720
I got everything working on my site like registering & logging in, except for for protecting all my pages...

I can bypass my login page and just type in URL http://www.mydomain/page.php

and still get to the protected page.

Once someone learns the link to the protected page,
they don't have to know the username and password.

Getting Alot Of Visitors Not Logging In Anymore To My Pages.. Also I Did Some Messing With The Process.php File To Have Users Re-direct To http://www.mydomain.index.php instead of main.php.. this is correct but the pages are not protected..

here my process.php
Code:
  1. <?
  2. /**
  3.  * Process.php
  4.  * 
  5.  * The Process class is meant to simplify the task of processing
  6.  * user submitted forms, redirecting the user to the correct
  7.  * pages if errors are found, or if form is successful, either
  8.  * way. Also handles the logout procedure.
  9.  *
  10.  * Last Updated: August 19, 2004
  11.  */
  12. include("include/session.php");
  13. class Process
  14. {
  15.    /* Class constructor */
  16.    function Process(){
  17.       global $session;
  18.       /* User submitted login form */
  19.       if(isset($_POST['sublogin'])){
  20.          $this->procLogin();
  21.       }
  22.       /* User submitted registration form */
  23.       else if(isset($_POST['subjoin'])){
  24.          $this->procRegister();
  25.       }
  26.       /* User submitted forgot password form */
  27.       else if(isset($_POST['subforgot'])){
  28.          $this->procForgotPass();
  29.       }
  30.       /* User submitted edit account form */
  31.       else if(isset($_POST['subedit'])){
  32.          $this->procEditAccount();
  33.       }
  34.       /**
  35.        * The only other reason user should be directed here
  36.        * is if he wants to logout, which means user is
  37.        * logged in currently.
  38.        */
  39.       else if($session->logged_in){
  40.          $this->procLogout();
  41.       }
  42.       /**
  43.        * Should not get here, which means user is viewing this page
  44.        * by mistake and therefore is redirected.
  45.        */
  46.        else{
  47.           header("Location: index.php");
  48.        }
  49.    }
  50.    /**
  51.     * procLogin - Processes the user submitted login form, if errors
  52.     * are found, the user is redirected to correct the information,
  53.     * if not, the user is effectively logged in to the system.
  54.     */
  55.    function procLogin(){
  56.       global $session$form;
  57.       /* Login attempt */
  58.       $retval $session->login($_POST['user'], $_POST['pass'], isset($_POST['remember']));
  59.       
  60.       /* Login successful */
  61.       if($retval){
  62.          header("Location: M1-Movies.php");
  63.       }
  64.       /* Login failed */
  65.       else{
  66.          $_SESSION['value_array'] = $_POST;
  67.          $_SESSION['error_array'] = $form->getErrorArray();
  68.          header("Location: index.php");
  69.       }
  70.    }
  71.    
  72.    /**
  73.     * procLogout - Simply attempts to log the user out of the system
  74.     * given that there is no logout form to process.
  75.     */
  76.    function procLogout(){
  77.       global $session;
  78.       $retval $session->logout();
  79.       header("Location: index.php");
  80.    }
  81.    
  82.    /**
  83.     * procRegister - Processes the user submitted registration form,
  84.     * if errors are found, the user is redirected to correct the
  85.     * information, if not, the user is effectively registered with
  86.     * the system and an email is (optionally) sent to the newly
  87.     * created user.
  88.     */
  89.    function procRegister(){
  90.       global $session$form;
  91.       /* Convert username to all lowercase (by option) */
  92.       if(ALL_LOWERCASE){
  93.          $_POST['user'] = strtolower($_POST['user']);
  94.       }
  95.       /* Registration attempt */
  96.       $retval $session->register($_POST['user'], $_POST['pass'], $_POST['email']);
  97.       
  98.       /* Registration Successful */
  99.       if($retval == 0){
  100.          $_SESSION['reguname'] = $_POST['user'];
  101.          $_SESSION['regsuccess'] = true;
  102.          header("Location: ".$session->referrer);
  103.       }
  104.       /* Error found with form */
  105.       else if($retval == 1){
  106.          $_SESSION['value_array'] = $_POST;
  107.          $_SESSION['error_array'] = $form->getErrorArray();
  108.          header("Location: ".$session->referrer);
  109.       }
  110.       /* Registration attempt failed */
  111.       else if($retval == 2){
  112.          $_SESSION['reguname'] = $_POST['user'];
  113.          $_SESSION['regsuccess'] = false;
  114.          header("Location: ".$session->referrer);
  115.       }
  116.    }
  117.    
  118.    /**
  119.     * procForgotPass - Validates the given username then if
  120.     * everything is fine, a new password is generated and
  121.     * emailed to the address the user gave on sign up.
  122.     */
  123.    function procForgotPass(){
  124.       global $database$session$mailer$form;
  125.       /* Username error checking */
  126.       $subuser $_POST['user'];
  127.       $field "user";  //Use field name for username
  128.       if(!$subuser || strlen($subuser trim($subuser)) == 0){
  129.          $form->setError($field"* Username not entered<br>");
  130.       }
  131.       else{
  132.          /* Make sure username is in database */
  133.          $subuser stripslashes($subuser);
  134.          if(strlen($subuser) < || strlen($subuser) > 30 ||
  135.             !eregi("^([0-9a-z])+$"$subuser) ||
  136.             (!$database->usernameTaken($subuser))){
  137.             $form->setError($field"* Username does not exist<br>");
  138.          }
  139.       }
  140.       
  141.       /* Errors exist, have user correct them */
  142.       if($form->num_errors 0){
  143.          $_SESSION['value_array'] = $_POST;
  144.          $_SESSION['error_array'] = $form->getErrorArray();
  145.       }
  146.       /* Generate new password and email it to user */
  147.       else{
  148.          /* Generate new password */
  149.          $newpass $session->generateRandStr(8);
  150.          
  151.          /* Get email of user */
  152.          $usrinf $database->getUserInfo($subuser);
  153.          $email  $usrinf['email'];
  154.          
  155.          /* Attempt to send the email with new password */
  156.          if($mailer->sendNewPass($subuser,$email,$newpass)){
  157.             /* Email sent, update database */
  158.             $database->updateUserField($subuser"password"md5($newpass));
  159.             $_SESSION['forgotpass'] = true;
  160.          }
  161.          /* Email failure, do not change password */
  162.          else{
  163.             $_SESSION['forgotpass'] = false;
  164.          }
  165.       }
  166.       
  167.       header("Location: ".$session->referrer);
  168.    }
  169.    
  170.    /**
  171.     * procEditAccount - Attempts to edit the user's account
  172.     * information, including the password, which must be verified
  173.     * before a change is made.
  174.     */
  175.    function procEditAccount(){
  176.       global $session$form;
  177.       /* Account edit attempt */
  178.       $retval $session->editAccount($_POST['curpass'], $_POST['newpass'], $_POST['email']);
  179.       /* Account edit successful */
  180.       if($retval){
  181.          $_SESSION['useredit'] = true;
  182.          header("Location: ".$session->referrer);
  183.       }
  184.       /* Error found with form */
  185.       else{
  186.          $_SESSION['value_array'] = $_POST;
  187.          $_SESSION['error_array'] = $form->getErrorArray();
  188.          header("Location: ".$session->referrer);
  189.       }
  190.    }
  191. };
  192. /* Initialize process */
  193. $process = new Process;
  194. ?>


is there something i have to change in the process.php file to redirect logged out users or guests back to my index.php to login when they reach a protected page?

Or Do I Have To Change Something In My Sessions.php

Code:
  1. <?
  2. /**
  3.  * Session.php
  4.  * 
  5.  * The Session class is meant to simplify the task of keeping
  6.  * track of logged in users and also guests.
  7.  *
  8.  * Written by:
  9.  * Last Updated: August 19, 2004
  10.  */
  11. include("database.php");
  12. include("mailer.php");
  13. include("form.php");
  14. class Session
  15. {
  16.    var $username;     //Username given on sign-up
  17.    var $userid;       //Random value generated on current login
  18.    var $userlevel;    //The level to which the user pertains
  19.    var $time;         //Time user was last active (page loaded)
  20.    var $logged_in;    //True if user is logged in, false otherwise
  21.    var $userinfo = array();  //The array holding all user info
  22.    var $url;          //The page url current being viewed
  23.    var $referrer;     //Last recorded site page viewed
  24.    /**
  25.     * Note: referrer should really only be considered the actual
  26.     * page referrer in process.php, any other time it may be
  27.     * inaccurate.
  28.     */
  29.    /* Class constructor */
  30.    function Session(){
  31.       $this->time time();
  32.       $this->startSession();
  33.    }
  34.    /**
  35.     * startSession - Performs all the actions necessary to 
  36.     * initialize this session object. Tries to determine if the
  37.     * the user has logged in already, and sets the variables 
  38.     * accordingly. Also takes advantage of this page load to
  39.     * update the active visitors tables.
  40.     */
  41.    function startSession(){
  42.       global $database;  //The database connection
  43.       session_start();   //Tell PHP to start the session
  44.       /* Determine if user is logged in */
  45.       $this->logged_in $this->checkLogin();
  46.       /**
  47.        * Set guest value to users not logged in, and update
  48.        * active guests table accordingly.
  49.        */
  50.       if(!$this->logged_in){
  51.          $this->username $_SESSION['username'] = GUEST_NAME;
  52.          $this->userlevel GUEST_LEVEL;
  53.          $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
  54.       }
  55.       /* Update users last active timestamp */
  56.       else{
  57.          $database->addActiveUser($this->username$this->time);
  58.       }
  59.       
  60.       /* Remove inactive visitors from database */
  61.       $database->removeInactiveUsers();
  62.       $database->removeInactiveGuests();
  63.       
  64.       /* Set referrer page */
  65.       if(isset($_SESSION['url'])){
  66.          $this->referrer $_SESSION['url'];
  67.       }else{
  68.          $this->referrer "/";
  69.       }
  70.       /* Set current url */
  71.       $this->url $_SESSION['url'] = $_SERVER['PHP_SELF'];
  72.    }
  73.    /**
  74.     * checkLogin - Checks if the user has already previously
  75.     * logged in, and a session with the user has already been
  76.     * established. Also checks to see if user has been remembered.
  77.     * If so, the database is queried to make sure of the user's 
  78.     * authenticity. Returns true if the user has logged in.
  79.     */
  80.    function checkLogin(){
  81.       global $database;  //The database connection
  82.       /* Check if user has been remembered */
  83.       if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
  84.          $this->username $_SESSION['username'] = $_COOKIE['cookname'];
  85.          $this->userid   $_SESSION['userid']   = $_COOKIE['cookid'];
  86.       }
  87.       /* Username and userid have been set and not guest */
  88.       if(isset($_SESSION['username']) && isset($_SESSION['userid']) &&
  89.          $_SESSION['username'] != GUEST_NAME){
  90.          /* Confirm that username and userid are valid */
  91.          if($database->confirmUserID($_SESSION['username'], $_SESSION['userid']) != 0){
  92.             /* Variables are incorrect, user not logged in */
  93.             unset($_SESSION['username']);
  94.             unset($_SESSION['userid']);
  95.             return false;
  96.          }
  97.          /* User is logged in, set class variables */
  98.          $this->userinfo  $database->getUserInfo($_SESSION['username']);
  99.          $this->username  $this->userinfo['username'];
  100.          $this->userid    $this->userinfo['userid'];
  101.          $this->userlevel $this->userinfo['userlevel'];
  102.          return true;
  103.       }
  104.       /* User not logged in */
  105.       else{
  106.          return false;
  107.       }
  108.    }
  109.    /**
  110.     * login - The user has submitted his username and password
  111.     * through the login form, this function checks the authenticity
  112.     * of that information in the database and creates the session.
  113.     * Effectively logging in the user if all goes well.
  114.     */
  115.    function login($subuser$subpass$subremember){
  116.       global $database$form;  //The database and form object
  117.       /* Username error checking */
  118.       $field "user";  //Use field name for username
  119.       if(!$subuser || strlen($subuser trim($subuser)) == 0){
  120.          $form->setError($field"* Username not entered");
  121.       }
  122.       else{
  123.          /* Check if username is not alphanumeric */
  124.          if(!eregi("^([0-9a-z])*$"$subuser)){
  125.             $form->setError($field"* Username not alphanumeric");
  126.          }
  127.       }
  128.       /* Password error checking */
  129.       $field "pass";  //Use field name for password
  130.       if(!$subpass){
  131.          $form->setError($field"* Password not entered");
  132.       }
  133.       
  134.       /* Return if form errors exist */
  135.       if($form->num_errors 0){
  136.          return false;
  137.       }
  138.       /* Checks that username is in database and password is correct */
  139.       $subuser stripslashes($subuser);
  140.       $result $database->confirmUserPass($subusermd5($subpass));
  141.       /* Check error codes */
  142.       if($result == 1){
  143.          $field "user";
  144.          $form->setError($field"* Username not found");
  145.       }
  146.       else if($result == 2){
  147.          $field "pass";
  148.          $form->setError($field"* Invalid password");
  149.       }
  150.       
  151.       /* Return if form errors exist */
  152.       if($form->num_errors 0){
  153.          return false;
  154.       }
  155.       /* Username and password correct, register session variables */
  156.       $this->userinfo  $database->getUserInfo($subuser);
  157.       $this->username  $_SESSION['username'] = $this->userinfo['username'];
  158.       $this->userid    $_SESSION['userid']   = $this->generateRandID();
  159.       $this->userlevel $this->userinfo['userlevel'];
  160.       
  161.       /* Insert userid into database and update active users table */
  162.       $database->updateUserField($this->username"userid"$this->userid);
  163.       $database->addActiveUser($this->username$this->time);
  164.       $database->removeActiveGuest($_SERVER['REMOTE_ADDR']);
  165.       /**
  166.        * This is the cool part: the user has requested that we remember that
  167.        * he's logged in, so we set two cookies. One to hold his username,
  168.        * and one to hold his random value userid. It expires by the time
  169.        * specified in constants.php. Now, next time he comes to our site, we will
  170.        * log him in automatically, but only if he didn't log out before he left.
  171.        */
  172.       if($subremember){
  173.          setcookie("cookname"$this->usernametime()+COOKIE_EXPIRECOOKIE_PATH);
  174.          setcookie("cookid",   $this->userid,   time()+COOKIE_EXPIRECOOKIE_PATH);
  175.       }
  176.       /* Login completed successfully */
  177.       return true;
  178.    }
  179.    /**
  180.     * logout - Gets called when the user wants to be logged out of the
  181.     * website. It deletes any cookies that were stored on the users
  182.     * computer as a result of him wanting to be remembered, and also
  183.     * unsets session variables and demotes his user level to guest.
  184.     */
  185.    function logout(){
  186.       global $database;  //The database connection
  187.       /**
  188.        * Delete cookies - the time must be in the past,
  189.        * so just negate what you added when creating the
  190.        * cookie.
  191.        */
  192.       if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
  193.          setcookie("cookname"""time()-COOKIE_EXPIRECOOKIE_PATH);
  194.          setcookie("cookid",   ""time()-COOKIE_EXPIRECOOKIE_PATH);
  195.       }
  196.       /* Unset PHP session variables */
  197.       unset($_SESSION['username']);
  198.       unset($_SESSION['userid']);
  199.       /* Reflect fact that user has logged out */
  200.       $this->logged_in false;
  201.       
  202.       /**
  203.        * Remove from active users table and add to
  204.        * active guests tables.
  205.        */
  206.       $database->removeActiveUser($this->username);
  207.       $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
  208.       
  209.       /* Set user level to guest */
  210.       $this->username  GUEST_NAME;
  211.       $this->userlevel GUEST_LEVEL;
  212.    }
  213.    /**
  214.     * register - Gets called when the user has just submitted the
  215.     * registration form. Determines if there were any errors with
  216.     * the entry fields, if so, it records the errors and returns
  217.     * 1. If no errors were found, it registers the new user and
  218.     * returns 0. Returns 2 if registration failed.
  219.     */
  220.    function register($subuser$subpass$subemail){
  221.       global $database$form$mailer;  //The database, form and mailer object
  222.       
  223.       /* Username error checking */
  224.       $field "user";  //Use field name for username
  225.       if(!$subuser || strlen($subuser trim($subuser)) == 0){
  226.          $form->setError($field"* Username not entered");
  227.       }
  228.       else{
  229.          /* Spruce up username, check length */
  230.          $subuser stripslashes($subuser);
  231.          if(strlen($subuser) < 5){
  232.             $form->setError($field"* Username below 5 characters");
  233.          }
  234.          else if(strlen($subuser) > 30){
  235.             $form->setError($field"* Username above 30 characters");
  236.          }
  237.          /* Check if username is not alphanumeric */
  238.          else if(!eregi("^([0-9a-z])+$"$subuser)){
  239.             $form->setError($field"* Username not alphanumeric");
  240.          }
  241.          /* Check if username is reserved */
  242.          else if(strcasecmp($subuserGUEST_NAME) == 0){
  243.             $form->setError($field"* Username reserved word");
  244.          }
  245.          /* Check if username is already in use */
  246.          else if($database->usernameTaken($subuser)){
  247.             $form->setError($field"* Username already in use");
  248.          }
  249.          /* Check if username is banned */
  250.          else if($database->usernameBanned($subuser)){
  251.             $form->setError($field"* Username banned");
  252.          }
  253.       }
  254.       /* Password error checking */
  255.       $field "pass";  //Use field name for password
  256.       if(!$subpass){
  257.          $form->setError($field"* Password not entered");
  258.       }
  259.       else{
  260.          /* Spruce up password and check length*/
  261.          $subpass stripslashes($subpass);
  262.          if(strlen($subpass) < 4){
  263.             $form->setError($field"* Password too short");
  264.          }
  265.          /* Check if password is not alphanumeric */
  266.          else if(!eregi("^([0-9a-z])+$", ($subpass trim($subpass)))){
  267.             $form->setError($field"* Password not alphanumeric");
  268.          }
  269.          /**
  270.           * Note: I trimmed the password only after I checked the length
  271.           * because if you fill the password field up with spaces
  272.           * it looks like a lot more characters than 4, so it looks
  273.           * kind of stupid to report "password too short".
  274.           */
  275.       }
  276.       
  277.       /* Email error checking */
  278.       $field "email";  //Use field name for email
  279.       if(!$subemail || strlen($subemail trim($subemail)) == 0){
  280.          $form->setError($field"* Email not entered");
  281.       }
  282.       else{
  283.          /* Check if valid email address */
  284.          $regex "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
  285.                  ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
  286.                  ."\.([a-z]{2,}){1}$";
  287.          if(!eregi($regex,$subemail)){
  288.             $form->setError($field"* Email invalid");
  289.          }
  290.          $subemail stripslashes($subemail);
  291.       }
  292.       /* Errors exist, have user correct them */
  293.       if($form->num_errors 0){
  294.          return 1;  //Errors with form
  295.       }
  296.       /* No errors, add the new account to the */
  297.       else{
  298.          if($database->addNewUser($subusermd5($subpass), $subemail)){
  299.             if(EMAIL_WELCOME){
  300.                $mailer->sendWelcome($subuser,$subemail,$subpass);
  301.             }
  302.             return 0;  //New user added succesfully
  303.          }else{
  304.             return 2;  //Registration attempt failed
  305.          }
  306.       }
  307.    }
  308.    
  309.    /**
  310.     * editAccount - Attempts to edit the user's account information
  311.     * including the password, which it first makes sure is correct
  312.     * if entered, if so and the new password is in the right
  313.     * format, the change is made. All other fields are changed
  314.     * automatically.
  315.     */
  316.    function editAccount($subcurpass$subnewpass$subemail){
  317.       global $database$form;  //The database and form object
  318.       /* New password entered */
  319.       if($subnewpass){
  320.          /* Current Password error checking */
  321.          $field "curpass";  //Use field name for current password
  322.          if(!$subcurpass){
  323.             $form->setError($field"* Current Password not entered");
  324.          }
  325.          else{
  326.             /* Check if password too short or is not alphanumeric */
  327.             $subcurpass stripslashes($subcurpass);
  328.             if(strlen($subcurpass) < ||
  329.                !eregi("^([0-9a-z])+$", ($subcurpass trim($subcurpass)))){
  330.                $form->setError($field"* Current Password incorrect");
  331.             }
  332.             /* Password entered is incorrect */
  333.             if($database->confirmUserPass($this->username,md5($subcurpass)) != 0){
  334.                $form->setError($field"* Current Password incorrect");
  335.             }
  336.          }
  337.          
  338.          /* New Password error checking */
  339.          $field "newpass";  //Use field name for new password
  340.          /* Spruce up password and check length*/
  341.          $subpass stripslashes($subnewpass);
  342.          if(strlen($subnewpass) < 4){
  343.             $form->setError($field"* New Password too short");
  344.          }
  345.          /* Check if password is not alphanumeric */
  346.          else if(!eregi("^([0-9a-z])+$", ($subnewpass trim($subnewpass)))){
  347.             $form->setError($field"* New Password not alphanumeric");
  348.          }
  349.       }
  350.       /* Change password attempted */
  351.       else if($subcurpass){
  352.          /* New Password error reporting */
  353.          $field "newpass";  //Use field name for new password
  354.          $form->setError($field"* New Password not entered");
  355.       }
  356.       
  357.       /* Email error checking */
  358.       $field "email";  //Use field name for email
  359.       if($subemail && strlen($subemail trim($subemail)) > 0){
  360.          /* Check if valid email address */
  361.          $regex "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
  362.                  ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
  363.                  ."\.([a-z]{2,}){1}$";
  364.          if(!eregi($regex,$subemail)){
  365.             $form->setError($field"* Email invalid");
  366.          }
  367.          $subemail stripslashes($subemail);
  368.       }
  369.       
  370.       /* Errors exist, have user correct them */
  371.       if($form->num_errors 0){
  372.          return false;  //Errors with form
  373.       }
  374.       
  375.       /* Update password since there were no errors */
  376.       if($subcurpass && $subnewpass){
  377.          $database->updateUserField($this->username,"password",md5($subnewpass));
  378.       }
  379.       
  380.       /* Change Email */
  381.       if($subemail){
  382.          $database->updateUserField($this->username,"email",$subemail);
  383.       }
  384.       
  385.       /* Success! */
  386.       return true;
  387.    }
  388.    
  389.    /**
  390.     * isAdmin - Returns true if currently logged in user is
  391.     * an administrator, false otherwise.
  392.     */
  393.    function isAdmin(){
  394.       return ($this->userlevel == ADMIN_LEVEL ||
  395.               $this->username  == ADMIN_NAME);
  396.    }
  397.    
  398.    /**
  399.     * generateRandID - Generates a string made up of randomized
  400.     * letters (lower and upper case) and digits and returns
  401.     * the md5 hash of it to be used as a userid.
  402.     */
  403.    function generateRandID(){
  404.       return md5($this->generateRandStr(16));
  405.    }
  406.    
  407.    /**
  408.     * generateRandStr - Generates a string made up of randomized
  409. &nb