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
Related
There are similar questions related to the topic but none of them have solved my problem. Its kind of weird but my $_SESSION is working on the same page but not on any other page. If I put isset($_POST['submit') the condition doesn't satisfy and without it the $_SESSION remains null.
This is my code.
This is the login page.
<!-- Login.php -->
<?php
session_start();
?>
<html>
<body>
<form method="post" action="profile.php">
<fieldset>
<legend>
Login
</legend>
<label> User ID :</label> <input type="text" placeholder="Username" name="user"><br>
<label> Password :</label> <input type="password" placeholder="Password" name="password">
<input type="submit" name="submit" value="Login">
</fieldset>
</form>
</body>
</html>
<?php
if(isset($_POST['submit'])){
$_SESSION['USER']= $_POST['user'];
$_SESSION['PASS']=$_POST['password'];
}
?>
This is where I want my session variable to appear.
<!-- profile.php -->
<?php
session_start();
echo "Session user is ".$_SESSION['USER']."<br>";
unset($_SESSION['USER']);
unset($_SESSION['PASS']);
session_unset();
session_destroy();
?>
This is what I have tried :
Changing form method to GET.
Using $_REQUEST and $_GET.
Using $_SESSION on the same page. It works on the same page.
Checking session id. The session on the other pages are present but values are either null or empty.
Running the code without isset(). In that case all the session variables remain NULL.
$_POST['submit'] and the rest of the post parameters are not available in Login.php
They are available only in profile.php because your form action points to it.
You may move the following code after the session_start() in profile.php.
if(isset($_POST['submit'])){
$_SESSION['USER']= $_POST['user'];
$_SESSION['PASS']=$_POST['password'];
}
Keep in mind that you unset the session values in the end of profile.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
}
`
I've created a working session (with help from here I might add) and I've managed to get it to store a variable across multiple files without any problems.
When $username isn't filled, there's a prompt for the user to submit their username and upon submitting $username is assigned the value of the user's name and the form is replaced with text, no longer prompting the user to enter a username, in theory.
Here's the code I have right now:
<?php
session_start();
?>
<header>
<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="style/main.css">
<title>webshop</title>
</header>
<div id="LogIn">
<?php
if(isset($_SESSION['username'])){
echo 'Current session username: '.$_SESSION['username'];
echo '<br />Destroy current session';
} else {
?>
<form class="form1" method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>" id="form1">
<fieldset>
<ul>
<p>Please enter your username to continue to the webshop.</p>
<label for="name">User Name:</label><span><input type="text" name="username" placeholder="User Name"
class="required" role="input"
aria-required="true"/></span>
<input class="submit transparentButton" value="Next" type="submit" name="Submit"/>
</ul>
<br/>
</fieldset>
</form>
<?php
if (isset($_POST['Submit'])) {
$_SESSION['username'] = $_POST['username'];
}
}
?>
</div>
cart<br />
index
The problem I'm having is that once the user has entered their username into the form and clicks "next", the page reloads and the form is still there. If you then refresh that page, it replaces the form with the text and the session variable $username parsed as plain text with a link to logout (session_destroy()).
My question is why do I have to refresh the page for the session variable to be displayed properly? Is it something to do with the if statement?
Thanks in advance.
You simply have a logic / ordering problem.
Move this piece of code that is currently below your form:
if (isset($_POST['Submit'])) {
$_SESSION['username'] = $_POST['username'];
}
to the top of your file, just below the session_start(), and it will behave as you intend.
The way your code is written now, the session variable is not set until AFTER the form displays. You want the session variable to be set BEFORE the form displays (if in fact the $_POST username is set).
I have created a HTML page which takes user-id and password from user and then check there validity through database. Till now i was directing them to another page after successful login. But now i want to update same page after login. Just like www.facebook.com ; when we are NOT logged in its asks for user-id and password, but if we are login our profile contents are displayed on the same page i.e. facebook.com. What i was doing; directing it to page "login.php" which of course you can access without login.
For example there is a page "movies.com" which allows user to watch some movies after login; before i was just directing them to another page say "successful_login.com" after they login. It was a funny approach, but was working for my college assignments.
PS. Am just a noob, sorry if i asked something funny.
<?php
if(mysql_connect("localhost","root","")==false)
{
die ("Connection Failed");
}
mysql_select_db("data");
if($_POST)
{
$id=$_POST["email"];
$pwd=$_POST["password"];
$pwd=hash( 'sha256', $pwd);
$sql=mysql_query("SELECT* FROM admin_data WHERE id='$id' AND pass='$pwd'");
if($sql)
{
header("Location: login.php");
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Document Structure
</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<form method="POST">
<h1>Welcome</h1>
<div class="inset">
<p>
<label for="email">Login</label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="password">PASSWORD</label>
<input type="password" name="password" id="password">
</p>
</div>
<p class="p-container">
<span>Forgot password ?</span>
<input type="submit" name="Login" id="Login" value="Log in">
</p>
</form>
</body>
</html>
To use the session variable you need to start session at the top.
session_start();
Now store the email value in the session in here.
if(mysql_num_rows()>0)//It was originally if($sql)but I am using mysql_num_rows
//The reason for saving the value in the session here is this.
First you want to make sure that user have valid credential to log in.
{
$_SESSION['email']=$id
header("Location: login.php");
}
In your form you can do something like this
session_start();//Start the session at the top so you can use the session variable.
then simply use if else statement.
if($_SESSION['email']==TRUE)
{
$email=$_SESSION['email'];
//Now you can run the query by using $email to fetch the record of the user.
}
else
{
//Show them a form or redirect them to another page.
}
Note:mysql is deprecated and is going to be dropped soon. Use mysqli or P.D.O
I am doing a project in school, I need to know a simple way to stop poeple from entering the site without a session. I have alot of pages I don't believe I spent the time pasting code on every page. Also I have menu bar that is included in every page thanks to php, so i was wondering wat type of code would I have to put in the menu to block user without a session. The rest of the content code is on the pages that I want to hide. I believe that you can login by typing out the url and allow users to see hidden pages that are for logged in users.
Please do not use a plain cookie. Sessions are the way to go. Or if can't use sessions and must use a cookie, sign the cookies first to be able to verify that your application was really the one to set it.
<?php
session_start();
if (!isset($_SESSION['authenticated'])) {
header('Location: login.php');
exit;
}
... whatever logged in users should see ..
If you don't want to use session, then use cookie.
<?php
/*Just add this piece of PHP code to top of any page you
don't want not-logged in users to see */
if (!isset($_COOKIE['logged']))
header("Location: login.php"); //It redirects the user to your login page
?>
<html>
<body>
...
</body>
</html>
Login page could be like this:
<?php
if (isset($_COOKIE['logged']))
header("home.php");
if ($_POST['submit']) {
//get username and password
$uname = $_POST['uname'];
$pass = $_POST['password'];
if ($uname=="correct" && $pass=="correct"){ //EDIT
setcookie('logged','1');
header("Location: home.php"); //Redirect to home page
}
else echo "Wrong combinaton!";
}
?>
<html>
<body>
<form action="login.php" method="post">
<label>Username</label><input type="text" name="uname" /><br />
<label>Password</label><input type="password" name="pass" /><br />
<input type="submit" name="submit" value="Login" />
</form>
</body>
</html>