PHP Session is NULL when going back to main index.php page - php

<?php
#this is dbconfig.php : assume all connection values are correct
session_start();
$ip = $_SERVER["REMOTE_ADDR"];
$host = "mysql.example.com"; /* Host name */
$user = "XXXX"; /* User */
$pass = "XXXX"; /* Password */
$dbname = "XXXX"; /* Database name */
$con = mysqli_connect($host,$user,$pass,$dbname);
?>
<?php
# THIS IS THE MAIN MENU (HOME PAGE)
# THIS PAGE FAILS TO GET SESSION WHEN MOVING TO HERE FROM THE PROFILE PAGE VIA BUTTON
include 'dbconfig.php';
var_dump($_SESSION); # returns NULL, should return same as profile
if (isset($_SESSION['username'])){
$username = $_SESSION["username"];
$password = $_SESSION["password"];
header('Location: https://example.com/profile');
}
?>
<?php
# THIS IS THE USERS PROFILE PAGE
include 'dbconfig.php';
var_dump($_SESSION); # This gives CORRECT data and verifies the session is set
$username; $password;
if (isset($_SESSION['username'])){
$username = $_SESSION["username"];
$password = $_SESSION["password"];
} else {
header("Location:https://example.com");
exit();
}
?>
<button>Logout</button>
<button>Home</button>
# WHEN PRESSING THIS BUTTON IT TAKES YOU TO HOME PAGE
# (ABOVE) EXCEPT IT DOESNT HAVE A SESSION ON THE HOME PAGE FOR SOME REASON
My question is why am I losing the session when I go from Profile page to Home page (no session on home page, I'm confused here.
Thank you!
I tried changing all links to match my host, EX : www.example.com to example.com (correct)
I tried adding session_start(); to all pages
I made sure all files were updated to SFTP correctly
Still I can't get the Home page to keep the session when the user returns to it from their profile page.
when I var_dump($_SESSION) on home page I get NULL

Related

Sessions and session variables are not working

I have a login script in Php. If the credentials are correct then the session is started, session variables are set and then redirected to the profile page. In the profile page, I have a script that redirects the user back to login page if they have not logged in.
Now, whenever I enter the correct credentials of the user and click on login, it redirects me back to the login page. To solve it, I commented out the code which was responsible for the redirection back to the login page. As a result, I got access to the profile page but I could not access the session variables.
And sometimes this code runs perfectly while sometimes it shows the above-stated problem.
The login code is as shown in the picture :
session_start();
require_once 'includes/config.php';
if(isset($_POST['login'])){
$user = trim($_POST['username']);
$pass = trim($_POST['password']);
$ch = $_POST['position'];
$stmt = $db->prepare("SELECT C_Name, PAN_id, Password FROM master_registration WHERE PAN_id = ?");
$stmt->bindParam(1,$user);
$stmt->execute();
$row = $stmt->fetch();
$username = $row["PAN_id"];
$Name = $row["C_Name"];
$hash = $row["Password"];
if(password_verify($pass, $hash)) {
session_start();
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $username;
$_SESSION["Name"] = $Name;
header("Location: main_folder/master/profile.php");
Login page code
The profile page code is as shown in the picture:
session_start();
require_once '../../includes/config.php';
if(!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] !== true){
header("location:../../index.php");
exit;
}
$user = $_SESSION['username'];
profile page code
The seems fine, but there is a problem in sessions, plus it works in localhost but when I hosted in CPanel the problem starts.
Please help anyone...
Sometimes the Cpanel need config on the PHP SESSION, php.ini
First yo can check the CPanel session.save_path and enabel output_buffering .
to used phpinfo()
Your code its correct. but if try session_start(); to inculed the config.php file
Change your profile pic code with this code...
Your logic is incorrect thatswhy you are redirected everytime
if(!$_SESSION['loggedin']) {
header("location: ../../index.php");
exit() ;
}

trying to figure of variable issues in php without using session for mysql database connection

I will describe my problem in two parts (previous problem and current problem).
Previous Problem:
Initially, on page3.php, I wasn't able to retrieve the username using the session variable and hiding //require('../myDBFolder/db.php'); solved the problem and I was able to see the username on that page.
Current Problem:
Since, I have commented out the line //require('../myDBFolder/db.php');, I am not able to access the other variables defined in db.php like $connection variable and hence I am trying to figure out how to make sure I have $connection variable available in page3.php.
A Quick explanation of the working of files is in the following order:
User submits username from page1.html, page2.php does the authorization work with db.php as required file and upon successful authorization, it directs the user to page3.php.
Please consider my files below:
page1.html
<form method="post" action= "page2.php" name="lform">
<span class="style1">User Name :</span>
<input type="text" name="user" size="25">
<input type="submit" value="login">
</form>
db.php
<?php
session_start();
$user = $_POST["user"];
$_SESSION['username']=$user;
$db_server = "localhost";
$db_name = "PracticeDB";
$db_user = $user;
$table_name_data = "collegestudents";
$connection = mysqli_connect($db_server,$db_user,$db_password) or trigger_error("Could Not Connect to the Database : ". mysqli_connect_error(), E_USER_ERROR);
$db = mysqli_select_db($connection , $db_name) or trigger_error("Could Not Select the Database : " . $db_name . ':' .mysqli_error($connection));
?>
page2.php
<?php
session_start();
require('../myDBFolder/db.php');
$user = $_POST["user"];
$_SESSION['username'] = $user;
$sql="SELECT * FROM $table_name_users WHERE username = \"$user\"";
$result=mysqli_query($connection,$sql) or trigger_error("Couldn't Execute Query in page2.php: ". mysqli_error($sql));
$num = mysqli_num_rows($result);
if ($num != 0) {
print "<script>";
print "self.location='page3.php';";
print "</script>";
} else {
echo "<p>you're not authorized";
}
?>
page3.php
<?php
session_start();
//require('../myDBFolder/db.php');
$user = $_SESSION['username'];
$sql = "SELECT * FROM $table_name_data WHERE username = '$user'";
$result = mysqli_query($connection,$sql) or trigger_error("Could Not Execute the Query ! : ". mysqli_error($connection));
?>
Troubleshooting Steps:
1) I have tried to include require('../myDBFolder/db.php'); in page3.php file and it solves the problem of $connection parameter but I don't see username coming onto that page via session for some reason and also by including //require('../myDBFolder/db.php'); in page3.php I will be making db connection twice as I have already done that in page2.php and haven't closed it.
2) Another thing, I was looking at some of the threads discussed before like this one, it seems like storing $connection in a session variable is not a good idea.
Just to point in a direction:
Change this
$user = $_POST["user"];
$_SESSION['username'] = $user;
to
if(isset($_POST["user"])){
$user = $_POST["user"];
$_SESSION['username'] = $user;
}
So, only update the SESSION if POST is given.
By the way, it is not good practise to give each user an db user account.
Your SQL check if a user is in the database, but your connectin also uses this username!? Rething that..
If you only use one db_user you can move the session username setting stuff completly from the db.php and move it to a better place (e.g. session.php).
the error of you dont see the username if you require db.php is :
in your db.php first thing to do is to put the username in the session so when you call it from the page3 you the code put blank in the session
this code
$user = $_POST["user"];
$_SESSION['username'] = $user;
There is two solution for that :
1 - put connection in one file and the session put in the other file
$user = $_POST["user"];
$_SESSION['username'] = $user;
in different file of connection
2 - the second is you put if condition before this code like this
if(!empty($_POST["user"])) {
$user = $_POST["user"];
$_SESSION['username'] = $user;
}
try it .

PHP session Login and Logout fails to proceed immediately

I have a PHP site with Login and Logout, using $_SESSION['userName'] to store the username of the logged in member.
But when people login, this does not happen immediately due to some reason. The same with the Logout script: It works, but not immediately. I have to try about 2-4 times before something happens.
Here is my Login code and Logout code:
Code: /login.php
session_start();
//=============Configuring Server and Database=======
$host = 'host';
$user = 'username';
$password = 'password';
//=============Data Base Information=================
$database = 'database';
$conn = mysql_connect($host,$user,$password) or die('Server Information
is not Correct'); //Establish Connection with Server
mysql_select_db($database,$conn) or die('Database Information is not correct');
//===============End Server Configuration============
//*******Form Information********
$userName=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
$passWord=md5($password); // Encrypted Password
//*********retrieving data from Database**********
$query = "select * from users where userName='$userName' and passWord='$passWord'";
$res = mysql_query($query);
$rows = mysql_num_rows($res);
//**********if $userName and $passWord will match database, The above function
//**********will return 1 row
if($rows==1)
//***if the userName and password matches then register a session and redrect
//***user to the Successfull.php
{
$_SESSION['userName'] = $userName;
header("location: ../index.php");
}
else
{
echo 'Incorrect username or password.';
}
exit;
Code: /logout.php
session_name('userName');
session_start('userName');
session_unset('userName');
session_destroy();
header("Location:index.php");
I really hope you can help me with this issue.
Edit 1: Okay now the login works, and the logout can now log the user out of all pages EXEPT the page the user where on, when they clicked "logout" ... Any ideas?
In PHP, Whenever you need session variables on the page. you must start session first on the same page.
By adding
session_start();
before any output message or character to the browser, else it will show a warning message.
lets come to the later part logout function.
where you should use
session_destroy();
to kill all the sessions.
a) perhaps browser cache is working, try add the following instructions before doing anything:
header("Pragma: no-cache");
header("Cache-Control: no-cache");
b) notice: session_start does not seem to have any parameter supported

Session not being saved after logging in

Another attempt at designing a user membership. Got to log in successfully, finds the data in the database. But in my index file, after logging in, it should check if I'm logged in and display links to my account instead of register and login. Here's the code:
<?php
session_start(); // Must start session first thing
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
And here is the login form code, where I think the problem is because it's not storing my session id:
<?php
if ($_POST['email']) {
//Connect to the database through our include
include_once "connect_to_mysql.php";
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']);
// filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = mysql_query("SELECT * FROM users WHERE email='$email' AND password=
'$password'AND emailactivated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_assoc($sql)){
// Get member ID into a session variable
$userid = $row["id"];
$_SESSION['id'] = $userid;
// Get member username into a session variable
$username = $row["username"];
$_SESSION['username'] = $username;
// Update last_log_date field for this member now
mysql_query("UPDATE users SET lastlogin=now() WHERE id='$userid'");
// Print success message here if all went well then exit the script
header("location: member_profile.php?id=$userid");
exit();
} // close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again
</font> <br/>
<br />Click here to go back to the login page.';
exit();
}
}// close if post
?>
Once again I'm following someone's tutorial and trying to implement it to my website and this would be perfect if it worked. Please advice why the $toplinks aren't being set after logging in.
I think the problem is, that you have to include the session_start() in every file where you want to use your session. Otherwise its working in the file like a normal array but not global. In your form i can't see that you start your session.
Edit: You need this only if you have 2 files. When you have only one file and include the other page its working when you include in once on top.
If you want to log out, then you should create a logout file, and include
session_destroy();
probably add also a href to get redirection link by doing something like:
header('location:index.php'); // will return you to index as soon as you logout.

How to make a secure session with php and mysql?

I have tried a session.php script which runs at the head of each page in my website to verify that the user has logged in before they can browse the site. However, now the process_login script won't load the secure landing page and it just reloads to the login page. I believe that my secure session is not being set correctly. Can someone further explain how this works to me?
This is the script, process_login, which executed when a user clicks login:
<?php
// Initialize session
session_start();
// Require database connection settings
require('config.inc');
// Retrieve email and password from database
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string(md5($_POST['password']));
$query = "SELECT * FROM $table WHERE email='$email' AND password='$password' LIMIT 1";
$result = mysql_query($query);
// Check email and password match
if(mysql_num_rows($result)) {
// Set email session variable
$_SESSION['email'] = $_POST['email'];
// Jump to secured page
header('Location: home.php');
}
else {
// Jump to login page
header('Location: index.php');
}
?>
and this is the session.php script which is in the head of each page that requires a user to be logged in:
<?php
if (isset($_SESSION['email']) == 0) {
// Redirect to login page
header('Location: index.php');
}
?>
You need to include the code
session_start();
in the your file session.php to access your session variables
Or you should make sure that session auto start is enabled on your php configuration.

Categories