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'];
?>
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
I am trying to create php multipage forms, and I use PHP sessions for this purpose.
However, when there is an error in user input and I want the form to ask user to fill in the form again with correct inputs, the forms field will not hold the data that the user has already put in so the user has to start things all over again.
How to make forms sticky with php session?
Thanks
My code is as bellow
<?php
// Session starts here.
if (!isset($_SESSION)) session_start();
?>
<form action="registration.php" method="post">
<center><h8>Please create your user name and password</h8></center>
<div class="imgcontainer">
<img src="phone.gif" alt="Welcome" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required value="<?php if(isset($_POST['username'])) echo $_POST['username'];?>">
<label><b>Password</b></label>
<input type="Password" placeholder="Enter Password" name="password" required>
<label><b>Confirm Password</b></label>
<input type="Password" placeholder="Confirm Password" name="confirm" required>
<span id="error" width=100%>
<!---- Initializing Session for errors --->
<?php
if (!empty($_SESSION['error'])) {
echo "<error>".$_SESSION['error']."</error>";
unset($_SESSION['error']);
}
if (isset($_POST['username'])){
$_SESSION['username'] = $_POST['username'];
echo $_SESSION['username'];
echo $_POST['username'];
}
?>
</span>
<br>
<input type="reset" value="Reset" />
<input type="submit" value="Next" />
</div>
and the registration php contains
<?php
if (!isset($_SESSION)) session_start();
// Checking first page values for empty,If it finds any blank field then redirected to first page.
if (isset($_POST['username']))
{
if (($_POST['password']) === ($_POST['confirm']))
{
foreach ($_POST as $key => $value)
{
$_SESSION['post'][$key] = $value;
}
}
else
{
$_SESSION['error'] = "Password does not match with Confirm Password.";
if (isset($_POST['username'])){
$_SESSION['username'] = $_POST['username'];
echo $_SESSION['username'];
echo $_POST['username'];
}
header("location: createlogin.php"); //redirecting to first page
}
}
Something like this:
<input name="var" value="<?= isset($_SESSION['var']) ? $_SESSION['var'] : null ?>" />
Try the other way around. Linking the form-action to the current page, and if all fields are valid; redirect it to the next page (registration.php). This way you'd still have all the post-data, you can process everything that needs to be saved in the session- and you can redirect after all of the logic is done.
My two cent would be keep the same page to validate the content and for the form.
You can include other PHP files from a single page depending on if the form is valid.
This way, you keep the same $_POST between both pages and don't need to store the posted data in a session variable.
Otherwise, if you want to keep the same architecture, you need to use the $_SESSION variables instead of the $_POST ones in your input value, such as the answer by delboy.
Replace:
<?php if(isset($_POST['username'])) echo $_POST['username'];?>
With:
<?php if(isset($_SESSION['username'])) echo htmlspecialchars($_SESSION['username']); ?>
^ Note: htmlspecialchars is used to prevent a reflected XSS if the users enters " as username.
The problem is, your data posted to registration.php, so you can't get the posted value in your original file. You are trying to use $SESSION but that's not recommended, and not right. Your whole solution is wrong.
Forget about session and separated files, put everything to registration.php file together.
You can check if user posted or not with $_SERVER['REQUEST_METHOD'] variable.
if($_SERVER['REQUEST_METHOD'] == 'POST'){
print 'Something just posted';
}
PS: Don't forget secure the password before you store it! :)
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 am aware that there are several topics about this but after hours of reading I still can't figure out what's going wrong.
I'm building a survey with a login screen at index.php. The user is required to insert their name and submit the form. The username should be saved and passed onto setup1.php.
This is part of my index.php:
<?php
session_start();
print session_id();
?>
<form id="login" method="POST" action="setup1.php">
<input id="participant" name="participant" type="text" size="20"/>
<input type="submit" name="start" value="Start"/>
</form>
<?php
$name = $_POST['participant'];
$_SESSION['username'] = $name;
?>
Start of setup1.php:
<?php
session_start();
print session_id();
print_r($_SESSION);
echo $_SESSION['username'];
?>
My $_SESSION variable is empty, I have nothing printed on the following page setup.php. I would appreciate if you could help.
Your $_POST code is in the wrong file. Your form is going to setup1.php, but you're trying to set the $_SESSION in your index.php.
You need to take it out of there and put it in setup1.php:
<?php
session_start();
if (!isset($_POST['participant'])) {
die('No $_POST data');
}
$_SESSION['username'] = $_POST['participant'];
print session_id();
print_r($_SESSION);
echo $_SESSION['username'];
?>
Also, make sure that you're using $_SESSION and not %_SESSION. I hope it was just a typo.
Your form hasn't been submitted when you set the $_SESSION['username'], i.e., $_POST['participant'] has no value.
You should move the piece of code below from index.php to setup1.php
<?php
$name = $_POST['participant'];
$_SESSION['username'] = $name;
?>
index.php
<?php
session_start();
?>
<form id="login" method="POST" action="setup1.php">
<input id="participant" name="participant" type="text" size="20"/>
<input type="submit" name="start" value="Start"/>
</form>
setup1.php
<?php
session_start();
if(isset($_POST['participant']) && ! empty($_POST['participant']))
{
$_SESSION['username'] = $_POST['participant'];
echo $_SESSION['username'];
}
?>`
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