I am trying to store sessions in the local storage of the user when they log in, but the expiry of the session is short and it is deleted every time I route to another page, and I could not figure out what had gone wrong. Below is some snippet of my code.
connect.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "ezcar2";
$conn = mysqli_connect($host, $username, $password, $database);
?>
ct_home.php
<body>
<?php
include_once 'connect.php';
session_start();
if (!isset($_SESSION['username'])) {
header("Location: ct_login.php");
exit();
}
?>
</body>
Whenever I refresh the page, I would be redirected back to ct_login.php. I would like for the session to stay until the user logs out.
EDIT (ct_login.php && setting the sessions)
<?php
include_once 'connect.php';
session_start();
if(isset($_POST['btnlogin'])){
$c_username = trim($_POST['txtusername']);
$c_password = trim($_POST['txtpwd']);
$sql_query = "SELECT * FROM tblcustomer WHERE CT_USERNAME = '$c_username' AND CT_PASSWORD = '$c_password'";
$sql_role = "SELECT * FROM tblcustomer WHERE CT_USERNAME = '$c_username' AND CT_PASSWORD = '$c_password' AND CT_ROLE = 'CAR OWNER'";
$sql_status = "SELECT * FROM tblcustomer WHERE CT_USERNAME = '$c_username' AND CT_PASSWORD = '$c_password' AND CT_STATUS = 'APPROVED'";
if($result = mysqli_query($conn, $sql_query)){
$rows = mysqli_num_rows($result);
if($rows == 1) {
if ($status = mysqli_query($conn, $sql_status)) {
$row_ = mysqli_num_rows($status);
if($row_ == 1) {
if($role = mysqli_query($conn, $sql_role)){
$rows_ = mysqli_num_rows($role);
if($rows_ == 1) {
//store username & password in session variable
$rec = mysqli_fetch_row($role);
$_SESSION['username'] = $rec[7];
$_SESSION['role'] = $rec[9];
header("Location: ct_home.php");
// session_start();
} else {
$rec = mysqli_fetch_row($result);
$_SESSION['username'] = $rec[7];
$_SESSION['role'] = $rec[9];
header("Location: ct_home.php");
// session_start();
}
}
} else {
echo('<script>alert("Account request is still pending. Please wait for confirmation email.");</script>');
echo "<meta http-equiv='refresh' content='0'>";
exit();
}
}
} else {
echo('<script>alert("Invalid Credentials. Please try again!");</script>');
echo "<meta http-equiv='refresh' content='0'>";
exit();
}
}
}
?>
Edit (#1) : The database connection is used to validate user login
Please let me know what else I can provide to draw a clearer picture of the whole situation. Many thanks in advance.
Related
I have been working is a website I have been dealing with a problem from a while, and now I know why it is happening, but not how to solve it. Please help!!
Page 1:
In the first page, login page set the $_SESSION['user_id'] is stored the value that are fetch in database user id. In same page can print session and it work properly(the $_SESSION['user_id'] is print) and also navigate the next page(user home).
page 2:
In page 2(user home) the $_SESSION['user_id'] is turned into null value why this happen?
most probably see this problem in, forgot to set the session start but I was set session start both page...
page 1
<?php
if (isset($_POST['sub'])) {
$user = $_POST['user'];
$pass = $_POST['pass'];
$con = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($con, "Database");
$qry = "select * from TABLE where username='$user' and password='$pass'";
$res = mysqli_query($con, $qry) or die("could not connect to mysql");
$row = mysqli_fetch_array($res);
$len = mysqli_num_rows($res);
if ($len <= 0) {
echo "<script>";
echo "alert('Oops.Username Or Password Incorrect!');window.location.href='login.php';";
echo "</script>";
} else {
session_start();
$_SESSION['id'] = $row['id'];
$_SESSION['message'] = $user;
$_SESSION['logout'] = "";
$id = $_SESSION['id'];
echo "<script>";
echo "alert('log in Success $id ');window.location.href='login.php';"; //$id is print correctly
echo "</script>";
}
}
?>
page 2
<?php
ob_start();
session_start();
if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
echo "$user"; // not printed
}
if (isset($_SESSION['message'])) {
$msg = $_SESSION['message'];
$_SESSION['message'] = "";
}
if (isset($_SESSION['logout'])) {
$msg = $_SESSION['logout'];
if ($msg == 'logout') {
header("location:login.php");
$_SESSION['message'] = "you must login first";
exit(0);
}
}
?>
<?php
echo "welcome"; // only print this string the above session are not work
?>
I also use this code before some project and it work correctly then why this time the session value not working?
use session in the start in first page, like this. Hopefully this will work
<?php
session_start();
if (isset($_POST['sub']))
{
$user=$_POST['user'];
$pass=$_POST['pass'];
$con=mysqli_connect("localhost","root","");
$db=mysqli_select_db($con,"Database");
$qry="select * from TABLE where username='$user' and password='$pass'";
$res=mysqli_query($con,$qry)or die("could not connect to mysql");
$row=mysqli_fetch_array($res);
$len=mysqli_num_rows($res);
if($len<=0)
{
echo"<script>";
echo"alert('Oops.Username Or Password Incorrect!');window.location.href='login.php';";
echo"</script>";
}
else
{
$_SESSION['id']=$row['id'];
$_SESSION['message']=$user;
$_SESSION['logout']="";
$id=$_SESSION['id'];
echo"<script>";
echo"alert('log in Success $id ');window.location.href='login.php';"; //$id is print correctly
echo"</script>";
}
}
?>
When I go to homepage.php, I would redirected to login.php and when I entered my login details and press submit, I am being directed to homepage.php. However, when I go to login.php, I am not automatically being brought to homepage.php despite being logged in.
login.php
<?php
error_reporting(E_ALL);
include("global.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$conn = new mysqli(server, dbuser, dbpw, db);
$userid = $_POST['txtLogin'];
$password = $_POST['txtPassword'];
$query = "SELECT userid from users where userid ='$userid' and password = '".md5($password)."'";
$result = $conn->query($query);
$count = mysqli_num_rows($result);
if($count == 1) {
$_SESSION['login_user'] = '$userid' ; {
header("Location: homepage.php");
exit();
}
}
}
?>
homepage.php
<?php
session_start();
if (!isset($_SESSION['login_user'])) {
header("Location: login.php");
}
?>
You have to add a condition in your login page whether $_SESSION['login_user'] is set or not.
<?php
error_reporting(E_ALL);
include("global.php");
session_start();
// before going further, first check whether session is active or not.
// if it is active then redirect user to homepage.php otherwise
// proceed further
if (isset($_SESSION['login_user'])) {
header("Location: homepage.php");
}
if($_SERVER["REQUEST_METHOD"] == "POST") {
$conn = new mysqli(server, dbuser, dbpw, db);
$userid = $_POST['txtLogin'];
$password = $_POST['txtPassword'];
$query = "SELECT userid from users where userid ='$userid' and password = '".md5($password)."'";
$result = $conn->query($query);
$count = mysqli_num_rows($result);
if($count == 1) {
$_SESSION['login_user'] = '$userid' ; {
header("Location: homepage.php");
exit();
}
}
}
?>
I have realized why i can't actually access userdata (after i am logged) old way to find the username is $_SESSION['username']; (assuming there is a row as 'username' in MySQL database)
So as i have a test account as "good25" (reason to choose numbers was to see if Alphanumeric inputs works fine.. its just checkup by me.. nevermind)
Problem :
assuming, i have rows in a table as 'username' and all of his information.. such as 'password', 'email', 'joindate', 'type' ...
On net i found out how to snatch out username from Session
<?php session_start(); $_SESSION('username'); ?>
successful!!
i had an idea to check if session is actually registering or no??
after a log on start.php i used this code
if(isset($_SESSION['username'])) { print_r($_SESSION['username']); }
the result was "1" (while i logged in using this username "good25")
any suggestions?
index.php (lets say, index.php just holds registration + Login form + registration script.. in login form, action='condb.php')
<?php
require 'condb.php';
if (isset($_POST['btn-signup']))
{
//FetchInputs
$usern = mysqli_real_escape_string($connection,$_POST['username']);
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$repassword = mysqli_real_escape_string($connection,$_POST['repassword']);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
//SearchUser
$searchusr = "SELECT username FROM $user_table WHERE username='$usern'";
$usersearched = mysqli_query($connection, $searchusr);
$countuser = mysqli_num_rows($usersearched);
//SearchEmail
$searcheml = "SELECT email FROM $user_table WHERE email='$email'";
$emlsearched = mysqli_query($connection, $searcheml);
$counteml = mysqli_num_rows($emlsearched);
//RegisteringUser
if ($countuser == 0)
{
if ($counteml == 0)
{
$ctime = time();
$cday = date("Y-m-d",$ctime);
$aCode = uniqid();
$adduser = "INSERT INTO $user_table(username, email, password, realname, activationcode, verified, joindate, type, points) VALUES ('$usern','$email','$password','$name','$aCode','n','$cday','Free',$signPoints)";
if (mysqli_query($connection, $adduser))
{
?><script>alert('You have been registered');</script><?php
}
else {
?><script>alert('Couldnt Register, please contact Admin<br><?mysqli_error($connection);?>');</script><?php
}
} else {
?><script>alert('Email already exists!');</script><?php
}
} else {
?><script>alert('Username already exists!');</script><?php
}
}
?>
condb.php
$connection = mysqli_connect($db_server, $db_user, $db_pass);
mysqli_select_db($connection, $db_name);
if(!$connection) {
die ("Connection Failed: " . mysqli_connect_error);
}
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($connection,$_POST['uname']);
$upass = mysqli_real_escape_string($connection,$_POST['upass']);
//FindUser
$finduser = "SELECT * FROM $user_table WHERE username='$uname' AND password='$upass'";
$findinguser = mysqli_query($connection,$finduser);
$founduser = mysqli_num_rows($findinguser);
//ConfirmPassword
if ($founduser > 0)
{
session_start();
$_SESSION['username'] = $username;
$_SESSION['username'] = true;
if ($findinguser != false)
{
while ($fetchD = mysqli_fetch_array($findinguser, MYSQLI_ASSOC))
{
$fetchD['username'] = $usernn;
$fetchD['email'] = $email;
$fetchD['userid'] = $uid;
$fetchD['realname'] = $rlnm;
$fetchD['points'] = $pts;
$fetchD['type'] = $membertype ;
}
header("Location: start.php");
} else {
echo mysqli_error();
}
} else {
header("Location: index.php");
?><script>alert('Wrong details, please fill in correct password and email');</script><?php
}
}
I am not asking you to build a script.. just little help please? (Thank you so so so so so much, as i am a self-learner, you don't have to say everything.. just a clue is enough for me)
may be you can try this code
<?php
require_once 'require.inc.php';
//session_start();
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($_POST['uname']);
$upass = mysqli_real_escape_string($_POST['upass']);
$search = mysqli_query($connection, "SELECT username, userid, password from $user_table WHERE username='$uname' AND password='$upass'");
$match = mysqli_fetch_assoc($search);
if ($match == 1 and $match['password'] == md5($upass))
{
$_SESSION['username'] = $match['userid'];
} else {
?>
<script>alert('Password or E-mail is wrong. If you havent registered, Please Register');</script>
<?php
}
}
if (isset($_SESSION['username']) or isset($match['userid'])){
header("Location:start.php");
}
if (isset($_POST['btn-signup']))
{
$name = mysqli_real_escape_string($_POST['name']);
$usern = mysqli_real_escape_string($_POST['username']);
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
$repassword = mysqli_real_escape_string($_POST['repassword']);
$name = trim($name);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
$query = "SELECT email FROM $user_table WHERE email='$email'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
$querytwo = "SELECT username FROM $user_table WHERE username='$usern'";
$resulttwo = mysqli_query($connection, $querytwo);
$counttwo = mysqli_num_rows($resulttwo);
if ($count == 0 AND $counttwo == 0)
{
if ($password == $repassword) {
if (mysqli_query($connection, "INSERT INTO $user_table(username, email, password, realname) VALUES ('$usern','$email','$password','$name')"))
{
?>
<script> alert ('Successfully registered'); </script>
<?php
}
}else {
?>
<script> alert ('The Password you entered, doesnt match.. Please fill in the same password'); </script>
<?php
}
}
else {
?>
<script> alert('Username or E-mail already exist'); </script>
<?php
}
}
?>
and this is for require.inc.php
<?php
global $username;
//require 'dconn.php';
session_start();
$_SESSION["username"] = $username;
$connection = mysqli_connect("localhost","root","", "test") or die(mysqli_error());
// Check Login
if (isset($_SESSION['username']) and isset ($match['userid']))
{
$Selection = "SELECT * FROM $user_table WHERE username='$username'";
$selectQuery = mysqli_query($connection, $Selection);
if ($selectQuery != false)
{
while ($fetchD = mysqli_fetch_assoc($selectQuery))
{
$usernn = $fetchD['username'];
$email = $fetchD['email'];
$uid = $fetchD['userid'];
}
} else {
echo mysqli_error();
}
}
?>
#suggestion, create session after user login and authorized then for each page start session and take session which you created and perform SQL queries using that session variable.
for example :
$_SESSION['user_name']=$row['username'];
for each page:
session_start();
$user_name=$_SESSION['user_name'];
SQL query
mysqli_query($con,"SELECT * FROM users where column_name='$user_name'");
I think you need to include dconn.php file in all files where you want to perform the mysql operation. If you have included it only in require.inc.php then you you it in all your other files.
Well I am trying to create kind of a social network but there is a problem with my session. So I am not able to visit other users profile. This is my code for loginwebsite1.php
<?php
ob_start();
session_start();
$connection = mysqli_connect('localhost', 'root', '123456789', 'register');
if (isset($_POST['email1'])) {
$email = mysqli_real_escape_string($connection, htmlentities($_POST['email1']));
}
if (isset($_POST['password1'])) {
$password = mysqli_real_escape_string($connection, htmlentities($_POST['password1']));
}
if (!empty($email) && !empty($password)) {
$query = "select id from register where email='$email' and password='$password'";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
if ($row > 0) {
$_SESSION['id'] = $row;
$_GET['id'] = $row;
header('location: new.php');
} else {
echo "sorry but the email-id or password is wrong";
}
} else {
echo "please enter your email-id or password or there";
}
?>
My session code goes like this:
<?php
ob_start();
session_start();
if (isset($_SESSION['id']) && !empty($_SESSION['id'])) {
$id = $_SESSION['id'];
foreach ($id as $fn)
$connection = mysqli_connect('localhost', 'id', 'password', 'register');
$query = "select firstname,lastname from register where id='$fn'";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
} else {
header('location: loginwebsite1.php');
}
?>
But when I try to enter like profile.php?id=9 it still opens the profile of the user who is logged in.
$id=$_SESSION['id'];
This line is where you problem is I believe. Here you get the ID number for the profile page to load from the $_SESSION variable when you should be getting it from the $_GET variable.
It should read:
$id=$_GET['id'];
you should also check if the $_GET['id'] is also set like this
$connection=mysqli_connect('localhost','id','password','register');
if(isset($_SESSION['id']) && !empty($_SESSION['id']) || !empty($_GET['id']))
{
$id=!empty($_GET['id'])? $_GET['id']: $_SESSION['id'];
foreach($id as $fn){
$query="select firstname,lastname from register where id='$fn'";
$result=mysqli_query($connection,$query);
$row=mysqli_fetch_array($result);
$firstname=$row['firstname'];
$lastname=$row['lastname'];
}
}else{
header('location: loginwebsite1.php');
}
also set your $connection variable to connect only once to your database.
I'm trying to fix my login page...
It works fine on the login.php with redirecting but on the index it doesn't redirect even if the session is empty. Any pointers? I'm new to this, so forgive me if it's really obvious.
<?php
require_once('../includes/config.php');
session_start();
if(!isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='no'){
// not logged in
header("location: login.php");
exit();
} else {
$_SESSION['loggedin'] = 'yes';
}
?>
<?php
include("../includes/config.php");
$error = NULL;
$atmpt = 1;
if (!isset($_SESSION)) {
session_start();
}
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='yes'){
// logged in
header("location: index.php");
exit();
}
if(isset($_POST['login']))
{
/* get username and password */
$username = $_POST["username"];
$password = $_POST["password"];
/* MySQL Injection prevention */
$username = mysqli_real_escape_string($mysqli, stripslashes($username));
$password = mysqli_real_escape_string($mysqli, stripslashes($password));
/* check for user in database */
$query = "SELECT * FROM admin_accounts WHERE username = '$username' AND password = '$password'"; // replace "users" with your table name
$result = mysqli_query($mysqli, $query);
$count = $result->num_rows;
if($count > 0){
//successfully logged in
$_SESSION['username']=$username;
$_SESSION['loggedin']='yes';
$error .= "<div class='alert alert-success'>Thanks for logging in! Redirecting you..</div>";
header("refresh:1;url=index.php");
} else {
// Login Failed
$error .= "<div class='alert alert-danger'>Wrong username or password..</div>";
$_SESSION['loggedin']='no';
$atmpt = 2;
}
}
?>
The line
session_start();
should be the very first line in the php script.
Just modify first three lines.
As session_start() should be put before any output has been put on the browser (even space).
<?php
session_start();
require_once('../includes/config.php');
if (empty($_SESSION['loggedin']) && $_SESSION['loggedin']=='no') {
...