This issue affects Firefox only. There are no issues in other browsers.
I have a custom login on my website. It works perfectly until I add the Twitter Timeline Embed code. When that code is added, the PHP session value changes when logging in. On signin.php, a php session value is generated. Upon pressing submit and going to success.php, the session value changes.
What could possibly be causing that and why only in Firefox?
Here is my code:
1.php
<?php
session_start();
//Prevent Cross-Site Request Forgeries//
$tokengf = md5(uniqid(rand(), TRUE));
$_SESSION['tokengf'] = "$tokengf";
$_SESSION['tokengf_timestamp'] = time();
////
?>
<form action="2.php" method="post" />
<h3> Enter Your Username:</h3>
<span class="question">What is your username? </span>
<p>
<label for="username">My username is:<br />
</label>
<input type="text" name="username" id="username" value="" size="40" maxlength="85" />
</p>
<input type="hidden" name="tokengf" value="<?php echo $_SESSION['tokengf']; ?>" />
<br />
<input type="submit">
</form>
<!--Twitter Timeline-->
<a class="twitter-timeline" href="https://twitter.com/gftravelsite" data-widget-id="412977135226081280">Tweets by #gftravelsite</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
And here's the page that gets submitted to:
2.php
<?php
session_start();
echo var_dump($_SESSION) . "<BR>";
echo print_r($_POST);
//Prevent Cross-Site Request Forgeries//
if ($_POST['tokengf'] != $_SESSION['tokengf']) {
echo "<br>post and session token values don't match.";
exit;
}
////
The browser output is:
array(2) { ["tokengf"]=> &string(32) "2e5b9797a3ba1e0b481f363b585c3bb1" ["tokengf_timestamp"]=> &int(1431234058) }
Array ( [username] => [tokengf] => 9bf4cca211d7a9874d954a434c21ac28 ) 1
post and session token values don't match.
The same exact page run using Chrome or IE gives this output as expected:
array(2) { ["tokengf"]=> &string(32) "fc28ab43754b40e6941a3f0208257de9" ["tokengf_timestamp"]=> &int(1431234321) }
Array ( [username] => [tokengf] => fc28ab43754b40e6941a3f0208257de9 ) 1
Thanks,
Tim
Related
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 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).
EDIT: Problem fixed. I appreciate the replies I got, both for their help and the rapid response they was. The two answers I got was both rather identical, but I chose one of them to mark it as solved.
I have, for some time tried to get this to work but I can't and thus I am coming here, hoping for help.
I am currently trying to create a login, register and comment function on my website. Registering is working, logging in with those credentials also work, and I have got a filter to prevent empty-field entries.
Once I log in I have it echo out the possibility to go to the comment page, and my plan there is to allow the users to write a comment, see the comments below, and the author name will be grabbed from their login username. See where I am going? That is exactly what's not working, though. I can't get it to grab the username from the login field, and I am quite sure it has something to do with that the website doesn't remember the login, and I'm unsure how to set cookies and such if thats where the fix would be.
So, TL;DR - How do I get the website to remember a login, then insert it into a field?
Above the code is the website design itself, connection with the database, and session_start();.
Login.php code
<?php
if(!isset($_POST['submit_login'])) {
// Checks whether anyone have clicked the submit button, as long as they don't, show the form
echo '
<div class="loginform">
<h2>Please login to continue</h2>
<br />
<form action="login.php" method="POST">
Username : <input type="text" name="username_login"><br />
Password : <input type="password" name="password_login"><br />
<br />
<input type="submit" name="submit_login" value="Submit">
</form>
</div>
';
}
if(isset($_POST['submit_login'])) {
// Checks whether they have clicked on the submit button or not, if they have, check if the fields are filled or empty, as well as check it with the database.
$username_login = $_POST['username_login'];
$password_login = $_POST['password_login'];
$loginCmd = "SELECT * FROM tblUsers WHERE username='$username_login' AND password='$password_login'";
$result = mysql_query($loginCmd);
if(empty($username_login)) {
echo "<center>Wrong username.</center>";
}
else if (empty($password_login)) {
echo "<center>Wrong password.</center>";
}
else if (mysql_num_rows($result) == 0) {
echo "<center>User does not exist.</center>";
}
else {
mysql_query($loginCmd);
echo '<center>Logged in. Welcome '.$username_login.' !</center> <br />';
echo '<center>View/post comments here</center>';
}
Comments.php code
<div class="commentform">
<h2>View and post comments and thoughts here!</h2>
<p>All fields required</p><br /><br />
<form action="comments.php" method="POST">
Author : <input readonly type="text" name="author" value=''> <br /><br />
Comment : <textarea name="comment" class="insertcomment"></textarea><br />
<br />
<input type="submit" name="submit" value="Submit">
</form>
</div>
<br />
<hr>
<br />
<?php
if(isset($_POST['submit'])) {
// Checks if they have clicked on the submit button, if they have, send it to the database
$comment = $_POST['comment'];
$author = $_POST['author'];
$insertComment = "INSERT INTO tblComments(comments, author) VALUES ('$comment', '$author')";
if(empty($comment)) {
echo "<center>No text found in comment field.</center>";
}
else if(mysql_query($insertComment) ) {
echo "<center>Comment posted</center>";
}
}
Once you validate the login then you can store the username in a session array which is persistent between pages :
<?php
// this goes on top of the php page where ever you want to use session variable
session_start();
//once user login is valid then you can store username like this
$_SESSION["username"]=$username; //$username is what you used while validating the login
?>
On some other page you can get this value back as long as you have session_start on top:
<?php
//2 nd page
session_start();
echo $_SESSION["username"];//This will print username which you stored while logging
?>
For more information on sessions visit w3schools or php.net
You have two options to store the username between pages: Cookies, which are stored on the user's computer, or sessions, which are stored on your server. Consider sessions for any security-based authentication as cookies can be easily manipulated by your users.
Cookies:
$expiry_time = time() + 604800; // Expire in 7 days (time is in seconds)
setcookie("username", "administrator", $expiry_time); // set the cookie
echo $_COOKIE["username"]; // read the cookie
Sessions:
session_start();
$_SESSION["username"] = "administrator"; // set the session variable
echo $_SESSION["username"]; // read the session variable
I've hit a road block in my PHP development where I am printing a form based on the existence of session variables. If there is a session variable called username, i don't want to print the login form, however this code only works when the page is refreshed.
Is there any way to overcome this issue using only PHP so that the form is hidden as soon as the user logs in rather than having to refresh.
Relevant code:
<?php
if(isset($_SESSION['username'])) {
print "Hello, " . $_SESSION['username'];
} else {
echo '<form method="post" action="' ?> <?php echo htmlentities($_SERVER['PHP_SELF']); ?>
<?php
echo '">
Username: <input type="text" name="username" class="username" />
Password: <input type="password" name="password" class="password" />
<input type="submit" value="Log in" class="submit_btn" />
</form>';
}
?>
...
<?php
...
if ($final_hash == $db_pass) {
$_SESSION['logged-in'] = true;
$_SESSION['username'] = $username;
} else {
print "wrong pass!";
}
Thank you for any help in advance.
You could submit the form with Ajax, set the session variables, then use java script to hide the form. You can't do it just with PHP because PHP is a server side language. Unless you send the client to the server (reload the page in some way) you can't hide it with out a client-side language.
I have had this issue intermittently for some time, but I only just had it happen repeatedly enough to actually trouble shoot it. It happened repeatedly in FF but I have seen it in Chrome as well.
I have login form as below, it is very simple, email address and password and a submit button
<form method="post" action="login.php" id="valid" class="mainForm">
<fieldset>
<div class="">
<label for="req1">Email:</label>
<div class="loginInput"><input style="width: 100%;" type="text" name="email" class="validate" id="req1" /></div>
<div class="fix"></div>
</div>
<div class="">
<label for="req2">Password:</label>
<div class="loginInput"><input style="width: 100%;" type="password" name="password" class="validate" id="req2" /></div>
<div class="fix"></div>
</div>
<input name="action" type="hidden" value="log_in" />
<div class="">
<div class=""><input type="checkbox" id="check2" name="remember_me" value="1"/><label>Remember me</label></div>
<input type="submit" value="Log me in" class="submitForm" />
<div class="fix"></div>
</div>
</fieldset>
</form>
Submitting the above form wouldn't log me in, it just displayed the login form again as if nothing was submitted. So I amended the login.php file that is submitted to, and at the very top added print_r($_POST);
When I submitted the form again all it displayed was an empty array. It was like the form variables just weren't being sent. I tried several accounts, and got a blank array each time.
I then tried to enter an email address that I new wasn't in the database, and to my amazement the $_POST array populated with the fake email and password. I then tried a real account again and it was blank.
The last thing I did was to deleted the session cookie in FF for the site, and then try again. To my surprise I could then log in OK. I logged in and out a few times after that with no problem at all!
So my question is: What was that session cookie doing to prevent the post variables from being sent (if that was what was actually happening) and why did it populate the $_POST array if I entered a fake email address? The print_r($_POST) I did was the very first thing in the script, before any other processing or includes, yet it still was empty??
I guess I don't really know how browsers deal with session cookies, but this behaviour has me completely clueless.
Any advice on how to troubleshoot this, or general session advice.
EDIT - PHP Code for the login.php
<?php
print_r($_POST);
include '../inc/init.php';
$action = fRequest::get('action');
if ('log_out' == $action) {
fSession::destroy();
fAuthorization::destroyUserInfo();
fMessaging::create('success', '<center>You were successfully logged out</center>');
}
if (fAuthorization::checkAuthLevel('user') || fAuthorization::checkAuthLevel('buser')) {
fURL::redirect('index.php');
}
if ('log_in' == $action) {
# Set session variables etc...
}
The init.php include at the top sets the database connetion strings and starts the session etc... I am using FlourishLib Un-Framework set of classes which includes a session class.
Thanks
try this code please
$actions = array('log_in', 'log_out');
$action = fRequest::getValid('action', $actions);
if ($action == 'log_out') {
fSession::clear();
fAuthorization::destroyUserInfo();
fMessaging::create('success', URL_ROOT . 'index.php', 'You were successfully logged out');
fURL::redirect(URL_ROOT . 'index.php');
}
if ($action == 'log_in') {
if (fRequest::isPost()) {
try {
$valid_login = fRequest::get('username') == 'yourlogin';
$valid_pass = md5(fRequest::get('password')) == 'md5(youpassword)';
if (!$valid_login || !$valid_pass) {
throw new fValidationException('The login or password entered is invalid');
}
fAuthorization::setUserToken(fRequest::get('username'));
fURL::redirect(fAuthorization::getRequestedURL(TRUE, URL_ROOT . 'index.php'));
} catch (fExpectedException $e) {
fMessaging::create('error', fURL::get(), $e->getMessage());
}
}
include VIEWS_DIR . DS . basename(__FILE__);
}