managing session file separately to include in all file - php

After logging, session will start. So i have to manage session.php in all my other files to manage session. Here is my login file:
<?php
if(isset($_POST['submit']))
{
include("connect.php");
$user=mysqli_real_escape_string($con, $_POST['email']);
$pass=mysqli_real_escape_string($con, $_POST['password']);
$sql="SELECT * FROM users WHERE email='".$user."' AND password='".$pass."' ";
$query=mysqli_query($con, $sql) or die(mysqli_error($con));
$count=mysqli_num_rows($query);
if($count==1)
{
$row=mysqli_fetch_array($query);
session_start();
$_SESSION['user_id']=$row['uid'];
}
else {
header("location:../index.php?error=1");
}
if(isset($_SESSION["user_id"])) {
header("location:../home.php");
}
}
?>
And in sessions.php:
<?php
session_start();
session_regenerate_id();
if($_SESSION["user_id"])
{
include("connect.php");
$m1 = "select * from users where uid='".$_SESSION['user_id']."'";
$m2 = mysqli_query($con, $m1);
$m3 = mysqli_fetch_array($m2);
$_SESSION['username'] = $m3['fname'].' '.$m3['lname'];
}
else
if(!isset($_SESSION['user_id']))
{
header("location:index.php");
}
?>
As the session is started in login.php itself, i get error in sessions.php 'Session is already started'. But if i remove session_start();, it redirects to index.php (login form). I am confused.
Can somebody help me in this?

Many commenters have pointed out issues with the question as asked. I can't comment, so I'll offer this bit of advice.
die(mysqli_error($con))
These errors should go to a log file, not printed for the user to see. Someone could find vulnerabilities in your system by reading the error message and exploit them. Don't make it easy for them!

<?php
session_start();
$user_id = $_SESSION['user_id'];
if(isset($_POST['submit']))
{
include("connect.php");
$user=mysqli_real_escape_string($con, $_POST['email']);
$pass=mysqli_real_escape_string($con, $_POST['password']);
$sql="SELECT * FROM users WHERE email='".$user."' AND password='".$pass."' ";
$query=mysqli_query($con, $sql) or die(mysqli_error($con));
$count=mysqli_num_rows($query);
if($count==1)
{
$row=mysqli_fetch_array($query);
$_SESSION['user_id']=$row['uid'];
}
else {
header("location:../index.php?error=1");
}
if(isset($_SESSION["user_id"])) {
header("location:../home.php");
}
}
?>
And in sessions.php:
<?php
session_start();
session_regenerate_id();
if($user_id)
{
include("connect.php");
$m1 = "select * from users where uid='".$user_id."'";
$m2 = mysqli_query($con, $m1);
$m3 = mysqli_fetch_array($m2);
$_SESSION['username'] = $m3['fname'].' '.$m3['lname'];
}
else
if(!isset($user_id))
{
header("location:index.php");
}
?>

Related

Extend expiry on sessions token PHP

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.

why session variable is empty to navigate the next page?

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>";
}
}
?>

php header not working online but working on my localhost.....why?

This works perfectly well on my localhost but when i hosted online, it does not logon and it echo logged on successful and error free. Pls what can be the cause for this?
<?php
session_start();
$_SESSION['user_logged']=$user;
$_SESSION['user_password']=$password;
$user = $_POST["username"];
$password = $_POST["password"];
include("include/connect.php");
$msg = array();
if(isset($_POST['submit'])){
foreach($_REQUEST as $key=>$val){
$$key=$val;
}
if(count($msg)==0){
$sql="SELECT username, password FROM admin WHERE username='$username' && password='$password'";
$res=mysql_query($sql) OR die(mysql_error());
if(mysql_fetch_array($res)>0){
$_SESSION['user_logged']= $user;
$_SESSION['user_password']=$password;
header("location:dashboard.php");
echo "You looged in Successfully";
} else{
$msg[]='Incorrect username/password';
}
}
}
?>
Below is the dashboard.php which its suppose to redirect to.
<?php
include('include/connect.php');
include('include/function.php');
if(isset($_REQUEST['mode']) )
{
$mode=$_REQUEST['mode'];
if($mode == 1)
{
$id=$_REQUEST['id'];
$sql="DELETE FROM enquiry WHERE id='$id'";
$result=mysql_query($sql);
}
}
$msg=array();
if(isset($_POST['submit'])){
$title=$_POST['news'];
$news_item=$_POST['news'];
if(empty($news_item)){
$msg[]='You must enter news in the column!';
}
if(empty($title)){
$msg[]='News Title must not be empty!';
}
else {
$sql = "SELECT * FROM news_file WHERE title='$title' ";
$res = mysql_query($sql) or die(mysql_error());
$result = mysql_fetch_array($res);
if($result > 0){
$msg[] = 'News with the same title has been added already';
} else {
$sql = "INSERT INTO news_file (title,news,date) VALUES ('$title','$news_item',Now())";
$result = mysql_query($sql);
$msg[]='News was successfully added';
}
}
}
?>
Try this.
<?php
session_start();
/*
These should be the other way round, as you are setting
the session variables with variables which have not been
initialised yet
*/
$user = $_POST["username"];
$password = $_POST["password"];
$_SESSION['user_logged']=$user;
$_SESSION['user_password']=$password;
include("include/connect.php");
$msg = array();
if(isset($_POST['submit'])){
foreach($_REQUEST as $key=>$val){
$key=$val; // Removed Erroneous double $
}
if(count($msg)==0){
$sql="SELECT
username,
password
FROM
admin
WHERE
username='$username'
AND
password='$password'";
// MySql does not accept && as a comparison operator.
$res=mysql_query($sql);
if(!$res)
{
var_dump(mysql_error());
exit;
}
else
{
if(mysql_fetch_array($res)>0)
{
$_SESSION['post'] = $_POST;
while(mysql_fetch_array($res)>0)
{
$_SESSION['user_logged']= $user;
$_SESSION['user_password']=$password;
header("location:dashboard.php");
echo "You logged in Successfully";
}
}
else
{
msg[]='Incorrect username/password';
}
}
?>
Looking at the code you have provided for dashboard.php, you are expecting there to be $_POST data, for a page which you have redirected to. Where you have redirected to the page, there will be no $_POST data for you to retrieve from the server.
I have amended my script above, to store the $_POST data in the session, so using that, you should be able to call your news items by calling $_SESSION['post']['news'], or if this is too long winded, simply re-assign the POST data once inside your dashboard.php script like so.
$post = $_SESSION['post'];
Then you can call it by using $post['news'].

echo don`t show when use unset global variables

I have started a session on config page, then $_SESSION['logged_out'] = 1; and on index page that:
if(isset($_SESSION['logged_out']))
{
echo "You have been logged out !";
unset($_SESSION['logged_out']);
}
But the echo not workig, like unset is before him. And i don`t understand why, please help me.
EDITED:
Config page:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
ob_start();
session_start();
include 'connection.php';
include 'functions.php';
$logged_in = 0;
if(isset($_SESSION['username']) && isset($_SESSION['password']))
{
$username = sec($link, $_SESSION['username']);
$password = sec($link, $_SESSION['password']);
$udata = get_row($link, "SELECT * FROM accounts WHERE Username= '$username' && Password= MD5('$password')");
if(isset($udata['ID']))
{
$logged_in = 1;
if(isset($_GET['logout']))
{
unset($_SESSION['username']);
unset($_SESSION['password']);
$_SESSION['logged_out'] = "1";
mysqli_query($link, "UPDATE accounts SET rpgon = '0' WHERE Username = '$username'");
header('location: index.php');
}
}
} ?>
Index page:
if(isset($_SESSION['logged_out']))
{
echo "You have been logged out !";
unset($_SESSION['logged_out']);
}?>
This is it ...
If echo doesn't show anything is because the if condition is evaluated to false. This mean that $_SESSION['logged_out'] isn't set.
You have to start_session() on every page that uses the $_SESSION. In fact if you are using $_SESSION anywhere in your site, its best to start it on all your pages.
So add start_session() just after the first <?php to ensure it is always started for all pages
<php
start_session();
. . .
if(isset($_SESSION['logged_out']))
{
echo "You have been logged out !";
unset($_SESSION['logged_out']);
}
Added after additional info given
I think this may be one of your problems
$udata = get_row($link,
"SELECT * FROM accounts
WHERE Username= '$username'
&& Password= MD5('$password')"
);
The && should be AND, then this query should return a result. You should really be checking the result status from all query command like so:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
session_start();
ob_start();
include 'connection.php';
include 'functions.php';
$logged_in = 0;
if(isset($_SESSION['username']) && isset($_SESSION['password']))
{
$username = sec($link, $_SESSION['username']);
$password = sec($link, $_SESSION['password']);
$udata = get_row($link, "SELECT * FROM accounts
WHERE Username= '$username'
AND Password= MD5('$password')"
);
// this would have shown the error in the sql query
// if it had been here before
if ( ! $udate ) {
echo mysqli_error($link);
exit;
}
// now this if will be executed
// although this if is probably no longer required
if(isset($udata['ID']))
{
$logged_in = 1;
if(isset($_GET['logout']))
{
unset($_SESSION['username']);
unset($_SESSION['password']);
$_SESSION['logged_out'] = "1";
mysqli_query($link, "UPDATE accounts SET rpgon = '0' WHERE Username = '$username'");
header('location: index.php');
// you should also follow a header() call with an exit;
exit;
}
}
}
?>

PHP Session to restrict access to file

index.php
session_start();
if(isset($_POST['login'])){
$username = mysqli_real_escape_string($con,$_POST['username']);
$pass = mysqli_real_escape_string($con,$_POST['userpass']);
$sel_user = "select * from users where user_name='$username' AND user_password='$pass'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0) {
$_SESSION['loggedIn'] = true;
$_SESSION['user_name']=$username;
header("location:display.php");
die();
}
else {
echo "<script>alert('Username or Password is not correct, please try again!')</script>";
}
}
display.php
session_start();
if(!$_SESSION['loggedIn']) {
header("location: index.php");
die();
}
Hello, I'm trying to figure out why my index.php is not letting me properly login and access my display.php The password and username is right, but keeps redirecting me to index.php Any ideas why?
Why don't you use Cookies instead?
In your login.php page instead of:
if($check_user>0) {
$_SESSION['loggedIn'] = true;
$_SESSION['user_name']=$username;
header("location:display.php");
die();
}
Do this:
if($check_user>0) {
$_SESSION['user_name']=$username;
$Month = 86400 + time();
setcookie('user', $username, $Month);
header("Location:display.php");
}
and then on your display.php
session_start();
if(!isset($_COOKIE['user']))
{
header("location:index.php");
die();
}

Categories