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! :)
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 writing a new PHP website, and have written a form, and the PHP code to handle the variables and the DB.
Trouble is, it won't even submit the form! Usually when you submit, if you hit F5 it will ask if you want to 'send again', it doesn't even do that. Something is clearly wrong, and I am a little rusty - but I thought I was ok with basic forms.
<?php
$username = isset($_POST['username']) ? $_POST['username'] : null;
echo "here: $username";
if(!isset($_SESSION['username'])) {
$_SESSION['username'] = $username;
} elseif (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
}
?>
<form method="post" action="/signup2/" name="signuprocess">
<input type="text" name="username">
<input type="submit" value="Sign Up">
</form>
After submitting, the $username doesn't appear after "here:".
What I am doing that's a bit silly??
I have tried to post the code on here, but it sees it as spam, as it is a sign up form.
What can I post to show the code, without it being seen as such?
When you "hit" F5 and the browser asks you to 'send again' is because you previously did a POST request. Otherwise, if your last request was, for example, a GET, the browser is not going to ask you anything. It will simply refresh the page.
try something like this
<?php
$username = $_POST['username'] ?? null;
echo "here: $username";
?>
<form method="post" action="" name="signuprocess">
<input type="text" name="username" value="<?php echo $username ?>">
<input type="submit" value="Sign Up">
</form>
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'm still new and trying to learn php. I have a form and everytime I run it I get an error displaying that the variable were not set when they should be. I'm definately missing something. Kindly explain what why is the variable $_POST['login_button'] not set the first time i run the page?
Code can be found below:
<?php
require 'connect.inc.php';
if (isset($_POST['login_button']) && isset($_POST['username']) && isset($_POST['password'])){
$login_button = $_POST['login_button'];
$username = $_POST['username'] ;
$password = $_POST['password'];
$password_hash = md5($_POST['password']);
if(!empty($username)&&!empty($password)){
$sql = "SELECT `id` FROM `golden_acres_username` WHERE `uname`='$username' AND '".$password_hash."'";
if($sql_run = mysql_query($sql)){
$query_num_rows = mysql_num_rows($sql_run);
}
if($query_num_rows==0){
echo'User name and password are incorrect';
}
else if($query_num_rows==1)
{
echo 'Username and password are correct';
}
}
else
{
echo 'Please fill in user name and password';
}
}
else
{
echo'Fields are not set';
}
?>
<form class="home_logon_area" action="test.php" method="POST">
Username:
<input type="text" name="username" />
Password:
<input type="password" type="password" name="password"/>
<input type="submit" name="login_button">
</form>
Thanks in advance,
Joseph
$_POST contains the result of submitting a form. If no form has been submitted yet, it will not contain anything.
Your script is working just fine; remove echo 'Fields are not set';, or use that line for code that should only run when the form hasn't been submitted yet.
The $_POST variable is set by the server to capture the data content sent by the browser as part of the form POST action. When the page is initially loaded, the browser has only executed/requested a GET call for the content of the page without sending the POST request.
Hope that helps!
This is simple to understand ;-)
First time the phpscript is executed to get the Form
So there will be no information at all (the visitor is new and have not seen the form before)
Then the User fills the form and press Submit button
The form is linked to the same side so the same phpscript gets executed again
Now you have the Formular values transmitted and you can acess them over $_POST
For more information look at php.net
Remove last else from your code and update the form with this one
<form class="home_logon_area" action="test.php" method="POST">
Username:
<input type="text" name="username" required />
Password:
<input type="password" type="password" name="password" required/>
<input type="submit" name="login_button">
</form>
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.