Page 1 of 1

Session Variables Undefined

Posted: Wed Jun 18, 2014 10:09 am
by tellydev
I am having a problem where my PHP session variables are becoming undefined.
The code starts execution on "login_page.htm" which accepts a user name and password and invokes the php script "login.php". "login.php" calls the function login which is located in the php script "myphpfunctions.php" and within the login function the session variables' values can be printed.
After returning from calling the "login" function within "login.php" the session variables' values can still be printed.

Then a successful login causes a page called "main_functions_page.htm" to be displayed which has a hyperlink to a page called "applicant_page.htm" which in turn runs a php script called "process_applicants.php". In "process_applicants.php", however, the session variables are now said to be undefined and its function call to the function "login_check" (defined in "myphpfunctions.php") also result in the session variables being undefined.

There error messages are as follows:

Undefined variable _SESSION in ..../process_applicant.php on line 10
Undefined variable _SESSION in ..../process_applicant.php on line 11
Undefined variable _SESSION in ..../myphpfunctions.php on line 103
Undefined variable _SESSION in .../myphpfunctions.php on line 104

Code: Select all

<?php
//Here is the code for login.php

include_once 'connection.php';
include_once 'myphpfunctions.php';
include_once 'make_connection.php';

 
start_secure_session(); // To start a secure PHP session
 
if (isset($_POST['username'], $_POST['password'])) {
    $username = $_POST['username'];
    $password = $_POST['password']; // The hashed password.
 


    if (login($username, $password, $mysqli) == true) {
        // Login success 
        //echo("Login successful");
   
        header('Location:http://oecsproject.meximas.com/main_function_page.htm');

    } else {
        // Login failed 
        //echo ("Login failed");
    }
} else {
    // The correct POST variables were not sent to this page. 
    echo 'Invalid Request';
}
?>
   </body>
</html>
There are comments by these lines in the code.

Code: Select all

<?php
//Here is the code for myphpfunctions.php

include_once 'connection.php';
include_once 'make_connection.php';

ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);

function start_secure_session() {

    $session_name = '12345';   // Set a custom session name

    // 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) {
        echo ("Could not open a secure session");
        exit();
    }
    // Gets current cookies params.
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"],
        $cookieParams["path"], 
        $cookieParams["domain"], 
        true,
        true);
    // Sets the session name to the one set above.

   session_name($session_name);
   session_start();            // Start the PHP session 
   session_regenerate_id(); 

  
}


function login($user_name, $password, $mysqli) {
    // Using prepared statements means that SQL injection is not possible. 

    if ($stmt = $mysqli->prepare("SELECT user_name, password, salt 
        FROM user_profiles
       WHERE user_name = ?
        ")) {
        $stmt->bind_param('s', $user_name);  // Bind "$user_name" to parameter.
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();
 
        // get variables from result.
        $stmt->bind_result($user_name, $database_password, $salt);
        $stmt->fetch();
 
        // hash the password with the unique salt.
        $password = hash('sha512', $password . $salt);
        if ($stmt->num_rows == 1) {
 
                 // Check if the password in the database matches
                // the password the user submitted.
 				$short_password = substr($password,0,80);
                if ($database_password == $short_password) {
                    // Password is correct!
//echo "password is correct <br/>";
                    // Get the user-agent string of the user.
                    $user_browser = $_SERVER
['HTTP_USER_AGENT'];
                    // XSS protection as we might print this value
                    $user_name = preg_replace("/[^a-zA-Z0-9_\-]+/", 
                                                                "", 
                                                                $user_name);
                    $_SESSION['user_name'] = $user_name;
                  $_SESSION['login_string'] = hash('sha512', 
                              $password . $user_browser);
  

        //echo "In login function user name: " . $_SESSION['user_name'] . "<br/>";
	//echo "In login function login string: " . $_SESSION['login_string'] . "<br/>";
                    // Login successful.
                    return true;
                } else {
		    echo ("Password is incorrect!!!");
                    return false;
                }
            
        } else {
            // No user exists.
            echo "No user exists!!!";
            return false;
        }
    } // end of if ($stmt = $mysqli->prepare.......)
}

function login_check($mysqli) {
echo 'In login_check function...';
        echo "In login_check user name: " . $_SESSION['user_name'] . "<br/>"; /*line 103 -- generating errors*/
	echo "In login_check login string: " . $_SESSION['login_string'] . "<br/>"; /*line 104* --generating errors */
 

    // Check if all session variables are set 
    if (isset($_SESSION['user_name'], 
                        $_SESSION['login_string'])) {
 
    
        $login_string = $_SESSION['login_string'];
        $user_name = $_SESSION['user_name'];

        // Get the user-agent string of the user.
        $user_browser = $_SERVER['HTTP_USER_AGENT'];
 
        if ($stmt = $mysqli->prepare("SELECT password 
                                      FROM user_profiles
                                      WHERE user_name = ? LIMIT 1")) {
            
           echo "In if mysqli->prepare statement <br/>";
            $stmt->bind_param('s', $user_name);
            $stmt->execute();   // Execute the prepared query.
            $stmt->store_result();
 
            if ($stmt->num_rows == 1) {
               echo "A row found in user_profiles table <br/>";
                // If the user exists get variables from result.
                $stmt->bind_result($password);
                $stmt->fetch();
                $login_check = hash('sha512', $password . $user_browser);
 
                if ($login_check == $login_string) {
                    // Logged In!!!! 
                    echo "User logged in <br/>";
                    return true;
                } else {
                    // Not logged in 
		    echo "User not logged in: ";
                    return false;
                }
            } else {
                // Not logged in 
		echo "User not logged in: ";
                return false;
            }
        } else {
            // Not logged in 
	   echo "User not logged in";
            return false;
        }
    } else {
        // Not logged in 
	echo "User not logged in";
        return false;
    }
}


?>

Code: Select all

<?php
//Here is the code for process_applicant.php
include_once 'connection.php';
//include_once 'make_connection.php';
include_once 'myphpfunctions.php';



ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);

        echo "In process_applicant session variable user name: " . $_SESSION['user_name'] . "<br/>"; /* line 10 - generating errors */
	echo "In process_applicant session variable login string: " . $_SESSION['login_string'] . "<br/>"; /* line 11 - generating errors*/


if (login_check($mysqli) == true) {
        // Add your protected page content here!
        

// Check connection
	if (mysqli_connect_errno())
	{
		echo "Failed to connect to MySQL: " . mysqli_connect_error();
		exit();
	}
	if (isset($_POST['last_name'])){		
		$last_name = $_POST['last_name'];
		echo 'last_name: '. $last_name. '<br/>';
	}

	if (isset($_POST['oth_names'])){
		$oth_names = $_POST['oth_names'];
		echo 'oth_names: '. $oth_names. '<br/>';
	}   

		
	if ($stmt = $mysqli->prepare("INSERT INTO applicants (last_name,other_names,sex,dob) values (?, ?,?,?)")) {
	    echo "In if statement prepare section...<br/>";
		
		$stmt->bind_param('ssss', $last_name,$oth_names,$applicant_sex,$dob);
		$stmt->execute();
		$stmt->close();

	} else{  
		echo "Prepared Statement Error: ". $mysqli->error . "br/>";
	}
} else { 
        echo 'You are not authorized to access this page, please login.';
}   
     
        
?>
The errors generated are the following
[text]

Notice: Undefined variable: _SESSION in /home/u797292730/public_html/process_applicant.php on line 10
In process_applicant session variable user name:

Notice: Undefined variable: _SESSION in /home/u797292730/public_html/process_applicant.php on line 11
In process_applicant session variable login string:
In login_check function...
Notice: Undefined variable: _SESSION in /home/u797292730/public_html/myphpfunctions.php on line 103
In login_check user name:

Notice: Undefined variable: _SESSION in /home/u797292730/public_html/myphpfunctions.php on line 104
In login_check login string:
User not logged inYou are not authorized to access this page, please login.

[/text]

Re: Session Variables Undefined

Posted: Wed Jun 18, 2014 2:17 pm
by requinix
You didn't call start_secure_session().

Re: Session Variables Undefined

Posted: Wed Jun 18, 2014 11:52 pm
by tellydev
Where exactly I am supposed to make a further call to start_secure_session()?

I just updated the code and added it just after the "include_once" statements in "process_applicants.php" and this is the error message that I now get

[text]
Notice: Undefined index: user_name in /home/u797292730/public_html/process_applicant.php on line 12
In process_applicant session variable user name:

Notice: Undefined index: login_string in /home/u797292730/public_html/process_applicant.php on line 13
In process_applicant session variable login string:
In login_check function...
Notice: Undefined index: user_name in /home/u797292730/public_html/myphpfunctions.php on line 102
In login_check user name:

Notice: Undefined index: login_string in /home/u797292730/public_html/myphpfunctions.php on line 103
In login_check login string:
User not logged inYou are not authorized to access this page, please login.
[/text]

So it seems now that the array index is what is not defined.

Re: Session Variables Undefined

Posted: Thu Jun 19, 2014 2:58 am
by requinix
Those are for debugging, yes? Relocate them to places where you know those bits of information have been set. For example, in process_applicant.php the session "user_name" only exists if the user is logged in, so put that statement in a place that only executes if the user is logged in. Meanwhile in login_check, it may not be set at the point you're trying to output it, so move the statement to a place that only executes if it was set.

Re: Session Variables Undefined

Posted: Sat Jun 21, 2014 8:05 pm
by tellydev
Hi requinix:

For some reason, I thought those places where I placed the "debugging code" were indeed places where the user needed to be logged in. I will try though to see if I come up with anything else

Telly