How to start and destroy session properly? - php

So, I have:
index.php(login and register form, welcome page, etc.)
login.php(it's a simple login verify php file, which executes when user press submit on index.php),
home.php (the site where the user redirects after logged in correctly)
logout.php(the reverse of login.php, redirects the user to index.php and destroy the session (I thought..)
The problem is, I can get at home.php, even before I sign in correctly, anytime.
I put start_session() on every page that needs $_SESSION variable, and put session_destroy() in logout.php as well.
So here are the php files' codes:
index.php
<body>
<?php
require_once('config.php');
if ($maintanance) {
echo "Az oldal karbantartás alatt van.";
}
else if ($db_conn_error) {
echo "Something went wrong according to database connection.";
}
else {
include('reg.php');
include('./templates/header.php');
?>
<section>
<form id="login_form" action="" method="POST">
<h2>Already a member? Sign in!</h2>
<p>Username: <input type="text" name="username"></p>
<p>Password: <input type="password" name="password"></p>
<input type="submit" name="login_submit" value="Sign In">
<?php include 'login.php'; ?>
</form>
<form id="reg_form" action="" method="POST" onsubmit="return validation();">
<h2>Sign up Now!</h2>
<p>Username: <input type="text" name="username" placeholder="min. 5 characters">
<span id="user_error"></span>
</p>
<p>Password: <input type="password" name="password" placeholder="min. 8 characters"></p>
<p>Password again: <input type="password" name="password_again"></p>
<p>E-mail: <input type="email" name="email" size="30"></p>
<p>Date of birthday:
<input type="number" name="bd_year" min="1950" max="2016">
<input type="number" name="bd_month" min="1" max="12">
<input type="number" name="bd_day" min="1" max="31">
</p>
<input type="submit" name="reg_submit" value="Sign Up">
</form>
</section>
</body>
</html>
<?php } ?>
login.php
<?php
include 'config.php';
if (isset($_POST["login_submit"]))
{
$username = $_POST["username"];
$password = $_POST["password"];
$query = "SELECT username, hashed_password FROM users WHERE username = '$username';";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rows_num = mysqli_num_rows($result);
$password_match_error_message = false;
if ($rows_num == 0) {
echo "<p class='login_error_msg'>This user doesn't exist!</p>";
}
else {
$password_match = password_verify($password, $row['hashed_password']);
if (!$password_match) {
echo "<p class='login_error_msg'>Wrong password!</p>";
}
else {
session_start();
$_SESSION["user"] = $username;
header("Location: home.php");
}
}
}
?>
home.php
<?php
session_start();
if (isset($_SESSION["user"])) {
?>
<!DOCTYPE html>
<html>
<head>
<title>Spookie - Social Network</title>
<link rel="stylesheet" type="text/css" href="./css/style.css">
</head>
<body>
<?php
include './templates/header.php';
?>
<?php } else { echo "You are not logged in!"; } ?>
</body>
</html>
logout.php
<?php
session_unset($_SESSION["user"]);
session_destroy();
header("Location: index.php");
?>
I know, it's hard to see what's really going on through the codes, the login works, but the session is not really.
The problem: I type in and home.php is always reachable, despite the fact I'm not logged in. The logout.php doesn't destroy the session or even the session couldn't start.
Thank you very much for your help! :)

The problem is in logout.php.
You should also claim session_start() to ensure you CAN remove the $_SESSION["user"] variable.
There may be other problems as I cannot see the whole code. Correct me if I am wrong.
Take a look at the another answer which explains the typical way to set up session variables

According to this manual: http://php.net/manual/en/function.session-destroy.php
In order to kill the session altogether, like to log the user out, the
session id must also be unset. If a cookie is used to propagate the
session id (default behavior), then the session cookie must be
deleted. setcookie() may be used for that.
The manual link has a full working example on how to do that. Stolen from there:
<?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();
?>

session_start() will start session.
session_destroy() will destroy session.
For setting session data you could do this.
`
$_SESSION['is_logged_in'] = true;
`
FOR CHECKING EXISTENCE OF SESSION or to check if user is logged in
`
If(isset($_SESSION['is_logged_in'] ) {}
else {
//redirect to login page
}
`

Related

How to display sessions information using php

I am trying to display session information like username, as user login through login page, the session has to capture user entered username and should display in page. Below i have tried php script, but its not echoing the username, Kindly check in the script for errors, thanks in advance.
<?php
session_start();
$_SESSION['test']= $_POST['myusername'];
$name= $_SESSION['test'];
echo $name;
?>
<form action="login.php" method="post">
<p>Username</p>
<input name="myusername" type="text" id="myusername" required>
<p>Password</p>
<input name="mypassword" type="password" id="mypassword"required></br>
<button><img src="http://icons.iconarchive.com/icons/webiconset/application/32/Register-icon.png" /></button>
</form>
login.php
Output i am getting is , simply its going to next page without displaying user name.
You can't access session data until after you call session_start(). So your first if statement is unnecessary and problematic as you can't check if a session variable exists until after you start your session. Also, make sure session_start() is called at the top of every page you wish to use sessions.
<?php
session_start();
$_SESSION['test']= $_POST['myusername'];
You must varify first that is session started or not. you can check it by using this code for Version PHP >= 5.4.0:-
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
or
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
or by this code for Version PHP < 5.4.0:-
if (session_id() === "") { session_start(); }
Then you can see all session stored values just by printing them as array.
echo "<pre>";
print_r($_SESSION);
then you can assign to session your post varible value like this.
$_SESSION['test']= $_POST['myusername'];
echo $_SESSION['test'];
You are setting session before post. Please use below code.
login.php
<?php
if(isset($_POST['myusername']))
{
// your code
session_start();
$_SESSION['test']= $_POST['myusername'];
}
?>
<form action="login.php" method="post">
<p>Username</p>
<input name="myusername" type="text" id="myusername" required>
<p>Password</p>
<input name="mypassword" type="password" id="mypassword"required></br>
<button><img src="http://icons.iconarchive.com/icons/webiconset/application/32/Register-icon.png" /></button>
</form>
newpage.php
<?php
session_start();
echo $_SESSION['test'];
?>

Redirect user who already logged in PHP

I want to redirect logged in users to home page(member-index.php), I have used the following code to accomplish this, but this doesn't work.
<?php
function redirect() {
header('location:member-index.php');
}
?>
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
if(isset($_SESSION['SESS_FIRST_NAME'])){
redirect();
}
?>
<form id="loginForm" name="loginForm" method="post" action="login-exec.php">
<input name="email" type="text" class="textfield" id="login" placeholder="username" />
<input name="password" type="password" class="textfield" id="password" placeholder="password"/>
<input type="submit" name="Submit" value="LOGIN" />
</form>
</body>
</html>
session variables at (login-exec.php)
$qry="SELECT * FROM members WHERE email='$login' AND passwd='".md5($_POST['password'])."'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) == 1) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
$_SESSION['SESS_FIRST_NAME'] = $member['fullname'];
The other pages with sessions, works perfectly fine, I could get and print the logged in user on another page, But couldn't get session work in login-form page..
Any help would be appreciated!
I'm surprised error reporting error_reporting(E_ALL); ini_set('display_errors', 1); didn't throw you a warning about outputting before header.
I.e.:
Warning: session_start(): Cannot send session cache limiter - headers already sent...
Move your <?php session_start(); ?> at the top of your code.
<?php session_start(); ?>
<?php
function redirect() {
header('location:member-index.php');
exit;
}
?>
and add exit; after your header to avoid further execution.
Also make sure all your files do not contain a byte order mark (BOM) and that there is no output before header. A space, HTML, nothing, not even a cookie, or anything else that would account as output.
All files should be saved in your code editor, as UTF-8 WITHOUT BOM.
I added this code at top of my login form, and it worked!
<?php
//Start session
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
header("location: member-index.php");
exit();
}
?>
Do this at the top of your file instead
<?php
session_start();
if(isset($_SESSION['SESS_FIRST_NAME'])){
header("location: member-index.php");
}
?>
<html>....the rest of your html
You can look at the php docs for header to see why you are having an issue. The paragraph that starts with 'Remember' specifically

missing session data after clicking browser back button

I'm developing a simple member management system with php, and I've met a problem:
The user logs in and it is redirected to a main page and the user ID is saved in the session; there are some links to other pages in the main page, after the user clicks and is trying to go back to main by pressing browser "Back" button, sometimes the user ID in the session is lost.
I've checked the session save path, a new session file is created when I click "Back" button, so I assume the session_start() creates a new session for it; but I still don't know why, it's a random case...
Is there any way to solve it?
main.php:
<?php session_start(); ?>
<?php
$echo_string = '
<body>
a
b
</body>';
if (!empty($_SESSION['user']))
echo $echo_string;
else
header("Location: login.php");
?>
login.php:
<?php
session_start();
if (isset($_POST['userLogin'])) {
$_SESSION['user'] = $_POST['userLogin'];
// check userLogin in db
...
}
header("Location: main.php");
?>
<form novalidate="" method="post" action="login.php">
<label class="hidden-label" for="Username">Username</label>
<input id="Username" name="userLogin" type="text" placeholder="Username" value="" spellcheck="false" class="">
<label class="hidden-label" for="Passwd">Password</label>
<input id="Passwd" name="userPassword" type="password" placeholder="Password" class="">
<input id="signIn" name="signIn" class="rc-button rc-button-submit" type="submit" value="Log in">
</form>
a.php:
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>...</head>
<?php
$echo_string = '...'; // a html format string
if (!empty($_SESSION['user']))
echo $echo_string;
else
header("Location: login.php");
?>
</html>
b.php is almost same as a.php
Thanks.
BR,
Sean
session_start()-docs:
"session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie."
so you see, that when a session exists it doesnt create a new, that means when you set something like $_SESSION['logged_in'] = true; you should check before if $_SESSION is already filled with your infos

Login Page Username and Password cannot be posted (PHP)

Username and password not appear on Page 2.PHP although I post it to Page2.PHP
Page1.PHP
<form name="form1" method="post" action="Page2.php">
<input type="text" name="txtLogin">
<input type="password" name="txtPWD">
<input type="submit" name="btnSub" value="go">
</form>
Page2.PHP
<?php
if(isset($_REQUEST['txtLogin']))
{
session_start();
$_SESSION['login']=$login;
}
if(isset($_SESSION['login']))
header('Location: detail.php');
else
header('Location: index.html');
?>
put this on page2.php
if(isset($_POST['txtLogin']) && isset($_POST['txtPWD']))
{
//get values & do other scripts like saving values on sessions
$user = $_POST['txtLogin'];
$pass = $_POST['txtPWD'];
echo $user.'<br>'.$pass;
}
else
{
//event here
}
The problem is here:
$_SESSION['login']=$login;
You are using the $login variable, but it isn't actually being set anywhere.
A few lines further up, we see that the login name is actually in $_REQUEST['txtLogin'], not $login. So you should be using that.
$_SESSION['login']=$_REQUEST['txtLogin'];
Hope that helps.
Check settings: enable_post_data_reading, request_order, variables_order, gpc_order on http://www.php.net/manual/en/ini.core.php

Session Value Not Working

I was trying to make a one page script with the action set to server php self but when running the script even after I type in the right password I am given "You Must Supply a Password". Am I doing this right. Please let me know my mistake
login.php
<?php
$pass = 'defense6';
if(isset($_POST['submit'])){
if(($_POST['password'] == $pass)) {
$_SESSION['password'] = md5($_POST['password']);
header('Location: index.php');
} else {
echo 'Password Invalid';
}
}
else {
echo 'You must supply a password.'.$_SESSION['password'] ;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
Password: <input name="password" type="password" /><br/><br/>
:
<input type="submit" name="submit" value="Login" style="float:right;" />
<br/>
<p></p>
</form>
index.php
<?php
$pass = 'defense6';
if($_SESSION['password'] == md5($pass)) {}
else {header('Location: login.php');}
?>
You need to add seesion_start() on every page you use session.
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
Add session_start() at the beginning of the pages that will help to maintain the session across requests.

Categories