Jump to content

Recommended Posts

I have some difficulty identifying why the session variables' values have disappeared in my PHP code.  When I try to echo their values, nothing shows up and when I try to compare the values, it does not work.

 

There are no error messages to indicate something has gone wrong?

 

Can someone assist?

x.txt

Link to comment
https://forums.phpfreaks.com/topic/289061-php-session-variables-unavailable/
Share on other sites

Hi Jazzman:

 

I am new to this PHPFreaks thing. I am not sure what is meant by posting code using the forums code tags. I have always noticed that I cannot copy and past directly into the forum's post pages. Can you direct me as to how I can post the code without using an attached file with the code?

 

Regards,

 

Telly

I am new to this PHPFreaks thing. I am not sure what is meant by posting code using the forums code tags. I have always noticed that I cannot copy and past directly into the forum's post pages. Can you direct me as to how I can post the code without using an attached file with the code?

 

I'm not sure why the forum doesn't let you paste the code. But to add code tags, you can use the method describe by davidannis. Or you can type out the tags:

 

your code goes here

 

 

If the code tags are added properly, you should get a code box like the following:

your code goes here

 

I have always noticed that I cannot copy and past directly into the forum's post pages

 

You should get an error message if you're trying to post a huge script. If so, you need to post only that piece(s) of code that relevant to your actual problem.

Edited by jazzman1
The starting point is the PHP code on the login form which has two text fields - one for the user name and one for the password.  Here is the code below.

<?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:../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>


-------------------------------------------------

The function start_secure_session() looks like this
function start_secure_session() {

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

    $secure = SECURE;
    // 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"], 
        SECURE,
        true);
    // Sets the session name to the one set above.

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

  
}

The login function is this
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.......)
}

In the login function the "echo" statements do print the values of the session variables $_SESSION['user_name'] and $_SESSION['login_string'].
 Then the next age thatdisplays calls the login_check function which is shown below and at the point the session variables have no values.
function login_check($mysqli) {
echo 'In login_check function...';

        echo "In login_check user name: " . $_SESSION['user_name'] . "<br/>";
	echo "In login_check login string: " . $_SESSION['login_string'] . "<br/>";
 

    // 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;
    }
}
Can anyone explain where I went wrong?

OK. I am giving a shot at using the code tags to explain my problem here below

 

 

Close, but no cigar. Only post the code in the box, not your text. And try and isolate your problem to the relevant code and only give us that much.

 

Is "start_secure_session" something that you have written? I don't find it in the manual is why I ask. Does it return a value that s/b checked?

function start_secure_session() {

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

    $secure = SECURE;
    // 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"], 
        SECURE,
        true);
    // Sets the session name to the one set above.

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

  
}

I am sorry,

 

I thought I had included it. Here is the code for the start_secure_session() function

Close, but no cigar.

 

When using


tags, this forum sometimes has issues with what comes after the box. However, the issue seems to go away if you preview the post before submitting it. To preview the post you can click the "More Reply Options" button.

Since, as I understand it, session data is stored on the server, and in order for a hacker to get to it he would first have to have the id, how does using a static id (set in your 'secure' function) make it more difficult to hack the session data what with everyone running with the exact same id?

The code I am using was modified from http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL and a static session id was first assigned and then it was regenerated.

 

However, I am not sure how this affects the fact that I cannot access the values of the session variables. Could you explain further?

 

Regards,

 

Telly

You shoud get some error messages without them I am affraid we cannot help you.Try to add the following error_reporting functions on the top of the file you call.

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

You stated this in reply #7:

Then the next age thatdisplays calls the login_check function which is shown below and at the point the session variables have no values.

I'm assuming a bit of a typo on 'the next age thatdisplays' that was meant to read 'the next page that displays'. If you're redirecting, are you restarting the session on the target page with session_start()? If not, usually php will throw an error, but if your error reporting is off you'll never know that. Insert the lines jazzman1 suggests on the page to which you redirect and see if it give you an error about undefined variable $_SESSION. If so, start the session again and let us know what happens.

Notice: Use of undefined constant SECURE - assumed 'SECURE' in /home/u797292730/public_html/myphpfunctions.php on line 14

Notice: Use of undefined constant SECURE - assumed 'SECURE' in /home/u797292730/public_html/myphpfunctions.php on line 27

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/u797292730/public_html/myphpfunctions.php:14) in /home/u797292730/public_html/myphpfunctions.php on line 32

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/u797292730/public_html/myphpfunctions.php:14) in /home/u797292730/public_html/myphpfunctions.php on line 32

Warning: session_regenerate_id() [function.session-regenerate-id]: Cannot regenerate session id - headers already sent in /home/u797292730/public_html/myphpfunctions.php on line 33

Warning: Cannot modify header information - headers already sent by (output started at /home/u797292730/public_html/myphpfunctions.php:14) in /home/u797292730/public_html/login.php on line 18

Thanks for the information on adding the 3 extra lines at the top for the error reporting. After adding these I get the errors as shown in the code window

Double check the script of this file and make sure that this constant is difened!

<?php
/**
 * These are the database login details
 */  
define("HOST", "localhost");     // The host you want to connect to.
define("USER", "sec_user");    // The database username. 
define("PASSWORD", "4Fa98xkHVd2XmnfK");    // The database password. 
define("DATABASE", "secure_login");    // The database name.
 
define("CAN_REGISTER", "any");
define("DEFAULT_ROLE", "member");
 
define("SECURE", FALSE);    // FOR DEVELOPMENT ONLY!!!!
session_set_cookie_params($cookieParams["lifetime"],
        $cookieParams["path"], 
        $cookieParams["domain"], 
        true,
        true);

Hi Maxxd:

 

Thanks for your help.

 

I reduced some errors by eliminating use of the "SECURE" constant and as seen in the code but the replacement code in the session_set_cookie_params functions (where the second to last argument value was replace with the value true instead on that SECURE constant

In login_check function...
Notice: Undefined index: user_name in /home/u797292730/public_html/myphpfunctions.php on line 101
In login_check user name: 

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

Hi Jazzman and All:

 

I got some errors in the myphpfunctions.php source file where the login_check function fires an error (which seems to suggest the array indexes of the $_SESSION array do not exist even though they were previously set in the login() function). I am einlcudeing the errors in the code window

Before looking the script into the login_check function, check first, if your login is being successful (or not) inside the login function and the both $_SESSION['user_name'] and $_SESSION['login_string'] variables are being defined.

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.......)
}

EDIT: For debugging your database errors you need to use mysqli::$error function.

Edited by jazzman1

and, even if the session variable are being set as expected in the login() function, if the session start on that page has failed (there would be php errors), the login isn't actually working because the session variables will only exist as local variables and won't be propagated between pages.

 

did you set the error_reporting/display_errors settings on each page or better yet those should be set in your php.ini on your development system so you don't need to remember to put them into code for debugging and remove them when you put your code onto a live server.

//login.php code below
<?php
include_once 'connection.php';
include_once 'myphpfunctions.php';
include_once 'make_connection.php';

 
start_secure_session(); // defined in "myphpfunctions.php"
 
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://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>

//--------------------------------------------------------------------
//myphpfunctions.php code below
<?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

    //$secure = SECURE;
    // 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
	echo "In login_check login string: " . $_SESSION['login_string'] . "<br/>"; //line 104
 

    // 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;
    }
}

?>

//-----------------------------------------------------------------
//process_applicants.php code below
<?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 */
	echo "In process_applicant session variable login string: " . $_SESSION['login_string'] . "<br/>";/*line  11*/

//if (1==1){
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_['ss_residence'])){ 
		$ss_residence = $_POST['ss_residence'];
		echo 'ss_residence: '. $ss_residence . '<br/>';
	}
	else
		$ss_residence = NULL;
   
	if (isset($_POST['data_file'])){
		$data_file = $_POST['data_file'];
		echo 'data file: '. $data_file. '<br/>';
	}

	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 (isset($_POST['email'])){
		$email = $_POST['email'];
		echo 'e-mail: '. $email. '<br/>';
	}   

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

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

	if (isset($_POST['otherOECSSystem'])){
		$otherOECSSystem = $_POST['otherOECSSystem'];
		echo 'Worked in Other OECS territory: '. $otherOECSSystem .'<br/>';
	}

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

	if (isset($_POST['ss_id_other'])){
		$ss_id_other = $_POST['ss_id_other'];
		echo 'Social Security ID number in other OECS territory: '. $ss_id_other. '<br/>';
	}

	   

	if (isset($_POST['id_doc_name'])){
		$id_doc_name = $_POST['id_doc_name'];
	echo 'Name of identification document file: '. $id_doc_name. '<br/>';
	} 

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

	
    $entered_by = "admin"; /* this should really assign the user name of the person logged in */
    $entry_date = "2014/06/08";/*$entry_date = Now();*/
    
    if ($sexType == "Male")
		$applicant_sex = 'M';
	else
		$applicant_sex = 'F';
		
	echo "applicant_sex: " . $applicant_sex . "<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.';
}   
     
        
?>
   </body>
</html>

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

 

There are comments by these lines in the code.

 

 

In the process_applicants.php file you also need to call start_secure_session() before using login_check(), otherwise you will get a notice of undefined variables, only the start_secure_session() function contains session_start() itself in your script. Even the both function are in the same file, any variable used inside a function is by default limited to the local function scope. Also, when using a php header function you need to call an exit command at the end.

 header('Location:http://main_function_page.htm'); exit; 
Edited by jazzman1
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.