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).
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! :)
I've got a login screen all setup but my php code doesn't seem to work with it. Can't find the issue either as the details I'm entering are correct but it is not displaying either of the outputs. 1 - being proceed to next page. 2 - being display message saying incorrect details. Atleast thats what I think it should be doing. My code is here;
<?php
session_start();
if (isset($_POST['login'])):
require_once('my_connect.php');
$username=$_POST['username'];
$password=$_POST['password'];
$my_query="SELECT * from loanusers where username='$username' AND password='$password'";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) >0):
while ($myrow = mysqli_fetch_array($result)):
$_SESSION['userid'] = $myrow["userid"];
$_SESSION['username'] = $myrow["username"];
$_SESSION['password'] = $password;
$_SESSION['usertype'] = $myrow["usertype"];
$_SESSION['authenticated'] = true;
echo "<b> Hi ".$_SESSION['username']." (ID: ".$_SESSION['userid']."), You are now logged in!</b>";
endwhile;
//header('Location: homepage.php');
else:
echo "<b>Username or Password incorrect</b>";
endif;
mysqli_close();
endif;
require_once 'loginheader.php';
?>
<html>
<body>
<h2>User Login</h2>
<div id="loginp"><p>Need an Account? <a href='adduser.php'><b>Sign Up</b> </p></a></div>
<table>
<form method="POST" action="homepage.php" autocomplete="off">
<input type="text" name="username" placeholder="Username...">
<br><br>
<input type="password" name="password" placeholder="Password...">
<br><br>
<input type="submit" name="loanlogin" value="Sign In" onclick="window.location.href='homepage.php'">
</form>
</table>
<br>
<div id="loginp"><p>Forgot your Password?<b> Click Here</b></p></a></div>
<body>
<html>
Check these two Ideas:
What are the values of $usernameand $password before you issue them to the select statement. (i would guess they are empty, then remove the onclick)
is their really a username with this password in the database.
i would guess it's the onclick in your submit. You don't need this event their and it is not submitting the Form element.
Note that your code looks vulnerable to SQL and XSS injections, it's important to learn about security too while learning in PHP :-)
The html post action was taking me to another page bypassing the login script.
I changed the action to index.php and the login now displays an error if the details are incorrect and takes me to the take page if details are correct.
Thanks All for helping
Remove the onclick Like user nv1t said as, there is already an form action referring to the same page. onclick functions are only for <button> tags
To pull the value, check this how to get a selected database value as a session variable in php - stackoverflow
Click the tick near the answer if this helped.
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'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