I have built a login page using php and pdo and created and logged in properly but after clicking log out button if I click back again it again goes to my page which appear only if logged in I even used session but it is not running properly even
<?php
include('connect.php');
session_start();
if(isset($_POST['logout'])){
{
unset($_SESSION['logged_in']);
session_destroy();
header("location:index12.php");
}
}
if(isset($_POST['login']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$errflag = false;
if($username == '' and $password == '') {
echo "you must enter username and password";
$errflag = true;
}
if ($errflag == false) {
SignIn($username,$password);
}
}
function SignIn($username,$password){
global $connect;
$search = $connect->prepare("SELECT * FROM users where username =
:username AND password = :password ");
$search->bindParam(':username',$username);
$search->bindParam(':password',$password);
$search->execute();
$count = $search->rowCount();
if($count> 0)
{
$_SESSION['username'] = $_POST['username'];
if(!isset($_SESSION['logged_in']))
header("Location: myfile.php");
}
else{
echo "wron email or password";
}
}
?>
the code of inner page is
<?php
echo "welcome to the website ";
echo "congrats you are logged in ";
?>
<html>
<head>
<title>
welcome here</title>
</head>
<body>
<form method ="POST" action = "login.php">
<button name="logout" style="float:right;">logout</button>
</form>
<h1><center>google is one of the best search engine</center></h1>
</body>
</html>
thankyou I updated the in the above manner but it is not working
Add bit of code session_start(); at the beginning of the page.
<?php
session_start();
if(isset($_POST['logout'])){
{
unset($_SESSION['logged_in']);
session_destroy();
header("location:index12.php");
}
}
?>
Also if you have not start session in connect.php ,you must need to start session by using session_start();
<?php
session_start();
include('connect.php');
I don't know how do you start your session but this a suggestion:
I generally write a new_session() function which looks like the following. I do prefer to set cookie params so we can have some control over it.
function new_session()
{
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams['lifetime'], $cookieParams['path'], $cookieParams['domain'], Sessions::SECURED_COOKIES, Sessions::HTTP_ONLY);
session_name('My_Awesome_App');
session_start();
session_regenerate_id();
}
And another one to destroy everything
function destroy_session()
{
session_unset();
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
session_destroy();
}
You can find the documentation about session_get_cookie_params() here
and about session_set_cookie_params() here
Back to your example
Using this new function you should call new_session() on top of your pages and your logout should look like.
new_session();
if (isset($_POST['logout'])) { {
unset($_SESSION['logged_in']);
destroy_session(); // our new function
header("location:index12.php");
}
}
Related
I have a login system and when the users login, they are sent to a new file called user.php. In the login file, I have this code:
$user = $check->fetch_assoc();
if (password_verify($_POST['password'], $user['password'])) {
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $user['username'];
header('location: user.php');
}
and when the user successfully logs in, he is sent to the user.php file and the code in the the file looks like:
<?php
// Start The session
session_start();
// Chaeck if the user is logged in.
if ($_SESSION['logged_in'] = false) {
$_SESSION['message'] = 'You must Login to continue use this section.';
header('location: error.php');
} else {
$username = $_SESSION['username'];
echo $username;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
</head>
<body>
<h1>
Welcome, <?php echo $username?>,
</h1>
</body>
</html>
But when the user logs in he gets the undefined index: username. I want to know why if I am using Sessions.
$user = $check->fetch_assoc();
if(!empty($user)) {
$passwordCheck = password_verify($_POST['password'], $user['password'])
if ($passwordCheck) {
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $user['username'];
header('location: user.php');
}
}
Here is modified welcome page
<?php
// Start The session
session_start();
// Chaeck if the user is logged in.
if (!isset($_SESSION['logged_in']) && $_SESSION['logged_in']=="") {
$_SESSION['message'] = 'You must Login to continue use this section.';
header('location: error.php');
} else {
$username = $_SESSION['username'];
echo $username;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
</head>
<body>
<h1>
Welcome, <?php echo $username?>,
</h1>
</body>
</html>
Please next time try to send a full code so that helping you will become a lot easier. Username is undefined probably because you did not initialize session session_start(); in your authentication script eg login.php that first handle the session. Again u will need to mitigate session fixation attack by generating new session for each login user session_regenerate_id();
$user = $check->fetch_assoc();
if (password_verify($_POST['password'], $user['password'])) {
// initialize session
session_start();
// prevent session fixation attack
session_regenerate_id();
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $user['username'];
header('location: user.php');
}
Optionally
At user.php
Remove the way your are performing session check and replace the code below.
you can check if users session is set using this simple script
<?php
// initialize session if session has not be initialize otherwise remove it
session_start();
if(!isset($_SESSION['username']) || (trim($_SESSION['username']) == '')) {
echo "you must login";
exit();
}else{
// login flows
}
?>
Pls send full code if this does not solve your problem
I tried a login and logout function in a signin bootstrap theme and it worked fine. But am not able to logout the session in my other tenplate when I use the same code which I used previously which worked. I tried all most all the solutions found in internet. I am getting a blank page when I click on Logout link.
login.php
<?php
session_start();
if (!empty($_SESSION['login_user'])) {
header('location:index.php');
}
?>
---html code---
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'foodchain');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if($_SERVER["REQUEST_METHOD"] == "POST") {
$myusername = mysqli_real_escape_string($db,$_POST['email']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT email,password FROM user_register WHERE email='$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQL_ASSOC);
$count = mysqli_num_rows($result);
if($count == 1) {
$_SESSION['login_user'] = $myusername;
header('Location:index.php');
}else {
$logmsg = "Invalid Username or Password";
}
}
?>
check_login.php
<?php
session_start();
if (!isset($_SESSION['login_user']) || empty($_SESSION['login_user'])) {
header('location:login.php');
}
?>
logout.php
<?php
session_start();
session_destroy();
header("Location:login.php");
die();
?>
index.php
<?php
include('check_login.php');
?>
Its perfectly working when I don't use the template(downloaded from some website), or when I use the bootsrap signin template.
You really should provide us with some source code, links to things that you've tried, what you've previously tried, what errors you received, etc. From what I can gather, you're looking for a logout page using sessions? Here's what I've got.
<?php
session_start();
session_destroy();
header('Location: ..');
?>
The key part is setting $_SESSION to an empty array.
From http://php.net/manual/en/function.session-destroy.php:
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
I have a session set up like this:
<?php
session_start();
include 'conconfig.php';
$con = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$email = $_POST['email'];
$pass = $_POST['pass'];
$query = "SELECT * FROM tempusers WHERE user='$email' AND pass='$pass'";
$result = mysqli_query($con,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_assoc($result);
if( $num_row >=1 ) {
echo 'true';
$_SESSION['uName'] = $row['uName'];
}
else{
echo 'false';
}
?>
and in my logout.php I have
<?php
session_start();
session_unset();
unset($_SESSION['uName']);
session_destroy();
header("Location:index.php");
?>
but none of the session_unset(); , unset() and session_destroy(); seems to be not working because after getting to the page I am still able to use browser Back button and back to the restricted page! besides the header() is not changing the page into index.php can you please let me know what I am doing wrong and how I can fix it?
Basically, I have a Log out Link in Restricted page which is like this
<a href="logout.php" >Logout</a>
Thanks
Update:
Here is the Session code which I have at the top of restricted page
<?php
session_start();
if(empty($_SESSION['uName'])){
header('Location: login.php');
}
?>
Try regenerating the session id and destroying all the data.
<?php
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(), '', 0, '/');
session_regenerate_id(true);
header("Location:index.php");
exit();
?>
How do I destroy a session in php?
the thing is when the user clicks the logout button the session will end and he will be redirected to the index.php here's my code
Customer.php
<?php
session_start();
#include("Connection.php");
if (isset($_POST['submit'])) {
$name = $_POST['customerName'];
$_SESSION['user'] = $name;
}
if (isset($_SESSION['user'])) { echo "Hello {$_SESSION['user']}, welcome back"; }
else{echo "walang tao";}
$sql="INSERT INTO ORDERS(Name) VALUES('$name')";
mysql_query($sql);
session_destroy();
?>
<button></button>
and this is from the index.php where the user wants to log in again
<?PHP
/* this must go before any html */
session_start();
if (isset($_SESSION['user'])) {
header("location: Customer.php");
}
?>
<div class="sign">
<h2>Welcome</h2>
<form action = "Customer.php" method = "POST">
Customer Name:<input type = "text" name="customerName">
<input type = "submit" name = "submit">
</form>
session_start();
session_destroy();
You may also used unset() function for free up session Environment.
if (isset($_SESSION['user']))
{
unset($_SESSION['user']);
header('location:index.php');
}
Include this file in your header and set the required settings in file.
It should work well.
<?php
session_cache_expire(20);
if (!isset($_SESSION)) {
session_start();
}
// set timeout period in seconds
$inactive = 1200; // timeout for the session
// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
$session_life = time() - $_SESSION['timeout'];
if($session_life > $inactive) {
$_SESSION = array();
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
header("Location: index.php"); // or whatever you prefer to do.
}
}
$_SESSION['timeout'] = time();
?>
If you aren't using the auth component then its really easy
public function logout(){
$this->Session->destroy();
// no cake we really want you to delete it because you suck
$this->Session->destroy();
}
//If you want complete destroy session then you can write.
session_destroy();
The session_unset() //function frees all session variables currently registered.
I have created an admin panel for a client in PHP, which requires a login. Here is the code at the top of the admin page requiring the user to be logged in:
admin.php
<?php
session_start();
require("_lib/session_functions.php");
require("_lib/db.php");
db_connect();
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: login_form.php');
die();
}
?>
Obviously, the if statement is what catches them and forces them to log in. Here is the code on the resulting login page:
login_form.php
<form name="login" action="login.php" method="post">
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="submit" value="Login" />
</form>
Which posts info to this controller page:
login.php
<?php
session_start(); //must call session_start before using any $_SESSION variables
include '_lib/session_functions.php';
$username = $_POST['username'];
$password = $_POST['password'];
include '_lib/db.php';
db_connect(); // Connect to the DB
$username = mysql_real_escape_string($username);
$query = "<grab username, hashed password from DB>;";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such user exists
{
header('Location: login_form.php?login=fail');
die();
}
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
db_disconnect();
$hash = hash('<myHashingFunction>', $password . $userData['salt']);
if($hash != $userData['password']) //incorrect password
{
header('Location: login_form.php?login=fail');
die();
}
else
{
validateUser(); //sets the session data for this user
}
header('Location: admin.php');
?>
and the session functions page that provides login functions contains this:
session_functions.php
<?php
function validateUser()
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['userid'] = $username;
}
function isLoggedIn()
{
if($_SESSION['valid'])
return true;
return false;
}
function logout()
{
$_SESSION = array(); //destroy all of the session variables
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
}
?>
I grabbed the sessions_functions.php code of an online tutorial, so it could be suspicious.
Any ideas why the user logs in to the admin panel, tries to do something, is forced to re-login, and THEN is allowed to do stuff like normal in the admin panel?
Be careful when using session_regenerate_id with redirects. In general. Don't.
remember to clear your browser cookies if the client switches servers :)
Is it just me, or is your isLoggedIn function really insecure? All you do is check for the existence of a session variable, which anyone could fake with a random value. You need to check the actual session ID/hash against a database of validated/logged in users.