In my website, after users log in and moves to a different page, their session is lost and on going back to the previous page(where their session was created) the page is blank, obviously because session is lost
I have two pages
<li class="nav-item">
<a class="nav-link " href="Options.php">Go to options</a>
</li>
<?php
//Start of session
session_start();
//Setting up databse connection
require_once 'databaseconnection.php';
$conn = mysqli_connect($db_hostname, $db_username, $db_password,$db_database);
if($conn->connect_error){
die("CONNECTION FAILED:".$conn->connect_error);
}
//Getting phone number and pasword provided by user in the login page (Not included in this)
if (isset($_POST['lpho']) &&
isset($_POST['lpass'])){
$lpho = get_post('lpho');
$lpass= get_post('lpass');
//Getting user information from database
$q="SELECT * FROM members WHERE phone='$lpho'";
if($q) {
//If record exists
$querymember = "SELECT * FROM members WHERE phone='$lpho' ";
$memberidentity = mysqli_query($conn,$querymember);
//To get number of rows
$rowsno = $memberidentity->num_rows;
//To fetch specific member column from database as an array
$memberrecords = $memberidentity->fetch_array(MYSQLI_NUM);
$count=$rowsno;
if($count>0){
//$reqpass is user's password from the database which is specific to array no [7]
$reqpass = $memberrecords[7];
//If given password matches the required password...
if($lpass==$reqpass){
//Session details passed
/*How do I put these in a cookie then load them on my next page */
$_SESSION['lpho'] = $lpho;
$_SESSION['lpass'] = $lpass;
}
}
}
}
?>
So my question in summary is how I can make a cookie in Account.php
that saves lpho
(phone) and lpass
(password) then loads it to Options.php
when user navigates to it.
<?php
echo "This is the options page";
?>
Using sessions in PHP with cookies relies on sending cookies in the headers of the page. This means that session_start()
must occur before any output from the page (as any output causes headers to be sent, and they can only be sent once per page). In your Account.php
file the first thing you do is output your <li>
block, which will cause a headers already sent
error when you try to set a cookie using session_start()
. Move the session_start()
to the beginning of each PHP file and that should resolve this problem. For example, in this file:
<?php
//Start of session
session_start();
?>
<li class="nav-item">
<a class="nav-link " href="Options.php">Go to options</a>
</li>
<?php
//Setting up databse connection
require_once 'databaseconnection.php';
Note that storing passwords in plain text is a very bad idea (in your case, both in your database and the session file on the server). You should use PHPs password_hash
and password_verify
functions to store and check passwords.