Variable $_SESSION does not want to be setted - php

So this is the code for page index.php: the $_SESSION["username"] variable seems to be not setted and I dunno why becuase in the login page I am using the isset control and the login is successful if I'm entering the right values;it is not if I am entering wrong username and password. I know I should "code" the password with md5 but right now that is not my problem :(
As you can see I'm redirecting to the index page after the login. From the index page I'm redirecting to the "home.php" page if the user already logged in. The problem is that after been doing the login,it keeps showing the login form and it is not redirecting me to home.php..
<?php session_start();
require_once "dbConn.php"; dbconnect();
if(isset($_SESSION["username"])){
echo $_SESSION["username"]; // TEST it never enters THERE!!!
echo'<p>Trasferimento alla home page</p>';
header("Refresh: 2; URL = home.php");
}
else{
echo'<div id=\"container\">';
echo'
<div id=\"content\">
<h2> You need to login :</h2>
<br/>
<form id="form1" name="form1" method="post" action="login.php">
<input type="text" name="username" id="username" />
<input type="password" name="password" id="password" />
<input type="submit" name="accedi" id="accedi" value="Accedi" />
</form>
<br/>
</div>';
include 'Footer.php';
echo'</div>';
}?>
And this is the login.php page:
<?php
require_once "dbConn.php"; dbconnect();
if(isset($_POST['username']) && isset($_POST['password'])) {
$username=mysql_real_escape_string($_POST['username']);
$pwd = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT * FROM user WHERE username='$username' AND password ='$pwd';");
if(mysql_num_rows($query) == 1){
$sessione =mysql_fetch_array($query);
$_SESSION["username"] = $sessione["username"];
echo $_SESSION["username"]; //TEST - it prints what I want: my username
$_SESSION["logged"] = true;
echo'Login effettuato con successo!';
header("Refresh: 2; URL = index.php");
}
else if((mysql_num_rows($query) == 0)){
echo'Utente non registrato o password errata';
header("Refresh: 2; URL = index.php");
}
}
?>
Thx all ;)

You forgot to call session_start() on your login page
<?php
require_once "dbConn.php"; dbconnect();
should be
<?php
session_start()
require_once "dbConn.php"; dbconnect();

Related

Session id is set even after logout

I'm trying to use session to keep the access to my website only to the authorized users.
Now, This is my main page:
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
require 'dbConfigBDO.php';
require 'message.php';
require 'SafeRedirect.php';
if (isset($_POST['username']) AND isset($_POST['pass']))
{
$_SESSION['message'] = '';
$username = $_POST['username'];
$password = $_POST['pass'];
$response= $conn->prepare('SELECT username,pass
FROM AdminTable
WHERE username = :nom
');
$response->bindValue(':nom',$username,PDO::PARAM_STR);
$response->execute();
$member = $response->Fetch();
$response->CloseCursor();
if(!$member) exit('اسم المستخدم غير صحيح');
if($password !== $member['pass']) exit('كلمة المرور غير صحيحه');
$_SESSION['id'] = $member['username'];
$_SESSION['message'] = htmlspecialchars($user). ' تم تسجيل دخولك بنجاح ';
safe_redirect('index.php');
exit;
}
?>
<!-- Log in:
First read name and password:-->
<form action="" method="post" id="form">
<fieldset class="form-item">
<legend>الدّخول</legend>
<label for="email">الاسم</label><input type="text" name="username" id="username"><br>
<label for="pass">كلمة المرور</label><input type="password" name="pass" id="pass">
</fieldset>
<fieldset class="form-submit">
<input type="submit" value="موافق">
</fieldset>
</form>
</body>
</html>
the problem here is when I redirect the user to index.php which checks as follows:
<?php
session_start();
require 'message.php';
require 'SafeRedirect.php';
$_SESSION['message'] = '';
$session_id = (isset($_SESSION['id'])) ? $_SESSION['id'] : null;
if($session_id == null)
{
$_SESSION['message'] = htmlspecialchars($user). ' Please sign in first... ';
safe_redirect('login.php');
exit;
}
?>
<a href="logout.php">
click here to log out</a>
Now when I press logout I shouldn't be able to access page index.php right?
the problem is I still can!
I tried to print the session ID and it does not change even after logout. I used
<?php
require 'SafeRedirect.php';
session_start();
unset($_SESSION["id"]);
session_regenerate_id(true);
session_destroy();
safe_redirect('login.php');
?>
my code use to work long time ago on another website but not now and I'm really confused what I did change since then.

Session logout without closing the session

We have a session logout script like:
<?php
//24 2 2015
session_start();
session_destroy();
header("location:login.php")
?>
now this script logouts and redirect it to login page where, username and password will be required to login again.
what if i wanted to have a temporary logout where after logging out it will direct us to a login page where it will only require password, cause session hasn't been destroyed and username is been passed to that page...
so, when you enter the password, it will check the input in database table where username = session username.
Hope i was clear.
The update::
templogout.php
<?php
//24 2 2015
session_start();
$_SESSION['temp_logout'] = true;
header("location:templogin.php")
?>
templogin.php
<?php
//24 2 2015
session_start();
?>
<form id="msform" action="templogincheck.php" method="post">
<fieldset>
<input type="password" name="password" placeholder="Enter password here" required />
<button type="submit" name="submit" class="submit action-button"> LogIn </button>
</form>
templogincheck.php
<?php
//15 2 2015
session_start();
$Cser =mysqli_connect("localhost","text","text","text") or die("Server connection failed : ".mysqli_error($Cser));
$password = md5($_REQUEST["password"]);
$mobile = $_SESSION['mobile'];
$s = "select * from users where password = '".$password."' and mobile = '".$mobile."'";
$result = mysqli_query($Cser,$s);
$count = mysqli_num_rows($result);
if($count>0)
{
$_SESSION["mobile"] = $mobile;
$_SESSION["login"]="1";
header("location:/index.php");
}
else
{
header("location:/templogin.php");
}
?>
index.php
<?php
//15 2 2015
session_start();
unset($_SESSION["temp_logout"]);
if(!isset($_SESSION["login"]))
header("location:login.php");
?>
I hope i did it right, but i have to presume i have something wrong cause it isn't working..
Am i passing the session mobile to the login check page?
user first login page:
<form id="msform" action="ulogincheck.php" method="post">
<fieldset>
<h2 class="fs-title">LogIn</h2>
<h3 class="fs-subtitle">Please Enter your details accordingly<br/><br/> <small>(case sensitive)</small></h3>
<input type="text" name="email" placeholder="Email" required />
<input type="text" name="mobile" placeholder="Mobile" required />
<input type="password" name="password" placeholder="Password" required />
<button type="submit" name="submit" class="submit action-button"> LogIn </button>
</form>
first logincheck page
session_start();
$email = $_REQUEST["email"];
$mobile = $_REQUEST["mobile"];
$password = md5($_REQUEST["password"]);
$s = "select * from users where email='".$email."' and password = '".$password."' and mobile = '".$mobile."'";
$result = mysqli_query($Cser,$s);
$count = mysqli_num_rows($result);
if($count>0)
{
$_SESSION["email"] = $email;
$_SESSION["mobile"] = $mobile;
$_SESSION["login"]="1";
header("location:/index2.php");
}
else
{
header("location:/usersignin.php");
You could add a "temp_logout" field to the $_SESSION variable and when you redirect the user to the login page, you can check for it $_SESSION["temp_logout"] and if it is true, add the username in the input field.
logout script:
<?php
//24 2 2015
session_start();
$_SESSION['temp_logout'] = true;
header("location:login.php")
?>
login page:
session_start()
...
//where the "username" input is
<input name="username" <?php if(isset($_SESSION["temp_logout"]){
echo 'value="'.$_SESSION["username"] .'" ';
} ?> />
...
after a successfull login:
<?php
session_start();
unset($_SESSION["temp_logout"]);
?>
Also, anywhere on the site, don't forget to check if the user is temporarily logged out; then immediatelly redirect him to the login page
it is really depend on your platform:
You can only unset something like password instead of destroying session,
unset($_SESSION['password']);
or set another key in session:
$_SESSION['loggedIn'] = false;
and redirect to login page.
also you can put username in cookie and destroy session.
setcookie
If you want to store username in cookie it is better to encrypt it for security reasons.

my login form always access denied

I created a simple login form. When I enter the correct username and password, it is always displaying the access denied message.
verify.php:
<?php
session_start();
$conn = mysqli_connect('localhost','root','') or die(mysqli_error());
mysqli_select_db($conn,'maindata') or die(mysqli_error($conn));
$uname=$_POST['username'];
$pass=$_POST['password'];
$password = md5($pass);
$result = mysqli_query($conn,"select * from users where username='$uname' and password='$password'")
or die("Could not execute the select query.");
$row = mysqli_fetch_assoc($result);
if(is_array($row) && !empty($row))
{
$validuser = $row['username'];
$_SESSION['valid'] = $validuser;
}
else
{
echo "<center></h1>Access Denied</h1></center>"."<br />";
echo "<center></h6>Please wait while you are redirected in 3 seconds</h6></center>"."<br />";
header('Refresh: 3; url=login.html');
}
if(isset($_SESSION['valid']))
{
header("Location:index.html");
}
login.html:
<?php
session_start();
if(isset($_SESSION['valid'])){
header("Location:index.html");
}
else
{
header("location:login.html");
}
?>
<form method="post" action="verify.php" class="login" class="contact_form">
<p>
<label for="login">Email:</label>
<input type="text" name="username" placeholder = "Enter Username Here...">
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" placeholder = "*******">
</p>
<p class="login-submit">
<button type="submit" class="login-button">Login</button>
</p>
<p class="forgot-password">Forgot your password?</p>
</form>
You'r code loops it self, Login.html checks if a user is logged in ( which they arrent because they cant login ) and redirects them from Login.html to Login.html meaning that you never enter your php code. You should not check if the user is already logged in when trying to access the login page.
Also you should consider making a file to check if the user is logged in, it could be something like this:
checkloggedin.php
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if($_SESSION['loggedin'] == false)
{
die(header("Location: ./index.php"));
}
?>
When you need to check if a user is logged in you can just start your pages off with:
<?php
include"checkloggedin.php"
?>

Why is my redirect after a succesful user login not working, but instead always loading the login page again?

Why when I input the correct username and password, it not redirect to index.php but instead reloads login.php ?
Help me to fix the following code:
<?php
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
require_once('conn/conn.php');
$user=$_POST['user'];
$pass=md5($_POST['pass']);
$addonq = "WHERE username='".$user."' AND password='".$pass."'";
$user = $koneksi->prepare("SELECT * FROM user ".$addonq."");
$user->execute();
$row = $user->fetch(PDO::FETCH_ASSOC);
if(empty($row['username'])){
echo "Your Login Name or Password is invalid";
}else {
$_SESSION['login_user'] = $user;
header("location: index.php");
}
}
?>
<form action="" method="post">
<label>UserName :</label>
<input type="text" name="user"/><br />
<label>Password :</label>
<input type="password" name="pass"/><br/>
<input type="submit" value=" Submit "/><br />
</form>
You need to add exit(); after header() to terminate the current process.
header("location: index.php");
exit();
Try this ..
Modify this line
$user = $koneksi->prepare("SELECT * FROM user ".$addonq."");
to
$user = $koneksi->prepare("SELECT * FROM user ".$addonq);

Logout problem /session not destroyed

I am having a problem when trying to login.. below is my code for the login
<?php
session_start();
include("functions.php");
connecttodb();
if(!empty($_SESSION['loggedin']) && !empty($_SESSION['username']))
{
echo "already logged in";
header("refresh:3; url=main.php");
}
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$sql="SELECT * FROM admin WHERE admin_username ='".$username."' AND admin_password= '".$password."'";
$result=mysql_query($sql) or die(mysql_error());
echo $sql;
if(mysql_num_rows($result) == 1)
{
$row = mysql_fetch_array($result);
$acc = $row['account'];
$_SESSION['username'] = $username;
$_SESSION['account'] = $acc;
$_SESSION['loggedin'] = 1;
echo "<h1>Success</h1>";
echo "<meta http-equiv='refresh' content='=2;panel.php' />";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Please click here to try again.</p>";
}
}
else
{
?>
<form method="post" action="login.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>
<?php
}
?>
My logout file
<?php
$_SESSION = array();
session_unset();
session_destroy();
echo "Logged Out !";
header("Location:login.php");
?>
The problem is that when i try to logout the session is not destroyed. When it redirects to the login page it says that im already logged in. How can i completely destroy the session when the users clicks on logout?
change your logout to the following:
<?php
session_start(); # NOTE THE SESSION START
$_SESSION = array();
session_unset();
session_destroy();
// echo "Logged Out!";
// Note: Putting echo "Logged Out!" before sending the header could result in a "Headers already sent" warning and won't redirect your page to the login page - pointed out by #Treur - I didn't spot that one.. Thanks...
header("Location:login.php");
exit(); # NOTE THE EXIT
?>
The session_start() is always require for each page when dealing with sessions.
Make sure you exit() the page when using header() with Location as the page will continue to execute.
I think you forgotten the session_start() before $_SESSION = array(); in your logout script

Categories