Jump to content

Recommended Posts

I'm trying to rewrite the old jpmaster77 login script that I used back in the day quite extensively, but I'm having problems getting the $form->error messages to the correct page.

 

Login form, on the index.php:

          <div>
            <h3>Login</h3>
            <form method="post" action="process.php" id="sublogin">

                  /* error message should be displayed here when username is empty or == username */
                  <p>
                  <?php
                  echo $form->error("user");
                  ?>

                  <input class="loginside" type="text" name="user" value="username" /> ?> <br />
                  <input class="loginside" type="password" name="pass" value="password" /> <br />
                  <input type="hidden" name="sublogin" value="1">
                  <input type="checkbox" name="remember">Remember me <br />
                  <input class="sublogin" type="submit" value="login" style="border: 0; margin: 5px 0 0 1px;" />
              </p>
            </form>
            Not registered yet? Sign up here!
          </div>



process.php

class Process
{
   /* Class constructor */
   function Process(){
      global $session;
      /* User submitted login form */
      if(isset($_POST['sublogin'])){
      	      	
      	      	
				$this->procLogin();
        
      }

      /**
       * Should not get here, which means user is viewing this page
       * by mistake and therefore is redirected.
       */
       else{
          header("Location: index.php");
       }
   }
   
   function procLogin(){
   
      global $session, $form;
      /* Login attempt */
      $_POST = $session->cleanInput($_POST);
      $retval = $session->login($_POST['user'], $_POST['pass'], isset($_POST['remember']));
      
		if($retval){
			header("Location: correct.php");
		}
		else{
		$_SESSION['value_array'] = $_POST;
                $_SESSION['error_array'] = $form->getErrorArray();
                header("Location: index.php");
		}

                /* if instead the $_SESSION and header I enter echo $form->error("user")
                   then the error message is displayed in process.php, and not in index.php
                */
   }

   
 }
 
$process = new Process;

?>

But when instead the $_SESSION and the header location I enter here echo $form->error("user"); then all is fine. But the error message should not be displayed in the process.php, but rather above the login form on the index.php



session.php
 

<?php

include "database.php";
include "form.php";

class Session

{
		var $time;
		
		function Session(){
			
			$this->time = time();
			$this->startSession();
			
		}
		
		function startSession(){
			
			$session_name = 'sec_session_id';   // Set a custom session name
	    $secure = true;
	    
	    // This stops JavaScript being able to access the session id.
	    $httponly = true;
	    
	    // Forces sessions to only use cookies.
	    if (ini_set('session.use_only_cookies', 1) === FALSE) {
	        header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
	        exit();
	    }
	    
	    // Gets current cookies params.
	    $cookieParams = session_get_cookie_params();
	    session_set_cookie_params($cookieParams["lifetime"],
	    $cookieParams["path"], 
	    $cookieParams["domain"], 
	    $secure,
	    $httponly);
	        
	    // Sets the session name to the one set above.
	    session_name($session_name);
	    session_start();           		 	// Start the PHP session 
	    session_regenerate_id(true);    // regenerated the session, delete the old one. 
		}		
		

		function login($subuser, $subpass, $subremember)
		{
			global $database, $form;
				
			/* username check */
			$field = "user";
			if(!$subuser || $subuser == "username")
			{
            $form->setError($field, "* Username incorrect");
			}

			/* password check */
			
			/* if e-mail welcome, check if user activated account */
      	
     	/* Return if form errors exist */
      if($form->num_errors > 0){
         return false;
      }	
      
      return true;
      
		}

		
		function cleanInput($post = array()) {
       foreach($post as $k => $v){
            $post[$k] = trim(htmlspecialchars($v));
         }
         
         return $post;
   	}
			
};

$session = new Session;
$form = new Form;

?>



form.php
 

<?php 
/**
 * Form.php
 *
 * The Form class is meant to simplify the task of keeping
 * track of errors in user submitted forms and the form
 * field values that were entered correctly.
 *
 * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC)
 * Last Updated: August 19, 2004
 */
 
class Form
{
   var $values = array();  //Holds submitted form field values
   var $errors = array();  //Holds submitted form error messages
   var $num_errors;   //The number of errors in submitted form

   /* Class constructor */
   function Form(){
      /**
       * Get form value and error arrays, used when there
       * is an error with a user-submitted form.
       */
      if(isset($_SESSION['value_array']) && isset($_SESSION['error_array'])){
         $this->values = $_SESSION['value_array'];
         $this->errors = $_SESSION['error_array'];
         $this->num_errors = count($this->errors);

         unset($_SESSION['value_array']);
         unset($_SESSION['error_array']);
      }
      else{
         $this->num_errors = 0;
      }
   }

   /**
    * setValue - Records the value typed into the given
    * form field by the user.
    */
   function setValue($field, $value){
      $this->values[$field] = $value;
   }

   /**
    * setError - Records new form error given the form
    * field name and the error message attached to it.
    */
   function setError($field, $errmsg){
      $this->errors[$field] = $errmsg;
      $this->num_errors = count($this->errors);
   }

   /**
    * value - Returns the value attached to the given
    * field, if none exists, the empty string is returned.
    */
   function value($field){
      if(array_key_exists($field,$this->values)){
         return htmlspecialchars(stripslashes($this->values[$field]));
      }else{
         return "";
      }
   }

   /**
    * error - Returns the error message attached to the
    * given field, if none exists, the empty string is returned.
    */
   function error($field){
      if(array_key_exists($field,$this->errors)){
         return "<font size=\"2\" color=\"#ff0000\">".$this->errors[$field]."</font>";
      }else{
         return "";
      }
   }

   /* getErrorArray - Returns the array of error messages */
   function getErrorArray(){
      return $this->errors;
   }
};
 
?>

Does anyone know why the $form->error("user") variable cannot be transfered to the index.php? Is something wrong with the session_start or something?

thanks in advance guys!

Edited by dde
Link to comment
https://forums.phpfreaks.com/topic/293737-lost-varriables-after-header-location/
Share on other sites

When you do a header() redirect you will lose any variables that were set during the current page execution. It is the same as if the user had entered that url directly into their browser - the requested page has no knowledge of anything that was done on the previous page. If you need to set values that will be available on subsequent page loads you should use COOKIE or SESSION values.

If you need to set values that will be available on subsequent page loads you should use COOKIE or SESSION values.

Aren't these SESSION values been set in the process.php?

 

 

		$_SESSION['value_array'] = $_POST;
                $_SESSION['error_array'] = $form->getErrorArray();
                header("Location: index.php");
Edited by dde

 

Aren't these SESSION values been set in the process.php?

 Yes, those were. But, you didn't mention those variables in your question. You asked

 

 

Does anyone know why the $form->error("user") variable cannot be transfered to the index.php?

 

You dumped a lot of code and asked why (what looks to be a class method) is not returning a value after the user is redirected via a header() function. I was not going to take 20-30 minutes to read through your code and try to decipher every line to figure out what values are specifically set where. Based on your question, my response was valid.

 

 

I found the problem. The "function startSession()" is not working the way I want it to work. When I replace everything inside this function with "session_start();" it all works.

 

So what is wrong with my startSession function?

I have no clue. I did take some time to try and follow the process flow of your code and gave up. It's too convoluted for me to digest without investing more time than I am willing. You're using "global" within a class?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.