echo don`t show when use unset global variables - php

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

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.

managing session file separately to include in all file

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

store $username and $file variables in the $_SESSION after login

From index.php I get the values of the username and password fileds with $_POST
index.php
if(isset($_POST["username"]) && isset($_POST["password"])){
$username = mysql_real_escape_string(strtolower($_POST['username']));
$password = mysql_real_escape_string($_POST['password']);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
checkUser($_SESSION['username'], $_SESSION['password']);
}
Then I store these $username and $password variables inside the $_SESSION and call a function checkUser($_SESSION['username'], $_SESSION['password'])); which sends two parameters. The checkUser() function executes inside lib.php
lib.php
session_start();
function checkUser($username, $password){
include "connection.php";
$result = mysqli_query($conn, "SELECT * FROM `data` WHERE `username` = '$username' AND `password` = '$password'") or die("No result".mysqli_error());
$row = mysqli_fetch_array($result);
$logic = false;
if (($row['username'] == $username) && ($row['password'] == $password)) {
$logic = true;
echo "HI,".$username;
?>
<a href='logout.php'>Log Out</a>
<?php
$file = $row['file'];
echo "<img src='images/users/".$file."' >";
}
else{
echo "Failed to login. Username or password is incorrect. Try again.";
}
}
This part is for showing the name of the user and the image according to it.
logout.php works
logout.php
unset($_SESSION["username"]);
unset($_SESSION["password"]);
unset($_SESSION["file"]);
header("Location: index.php");
session_destroy();
The problem is when I navigate from one page to another, the $_SESSION variable becomes empty. Something is wrong with session. Please help me.
in the php pages you need to access session variable add session_start() after the starting <?php code

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();
}

Login Not Working PHP MySQL

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') {
...

Categories