I've been working on this problem over the last couple days where a post redirect get function works in chrome, but mot other browsers like firefox and safari.
The code below should start a session, set $_POST variables as $_SESSION variables if they exist, assign the sessions to a variable, and then unset and destroy the sessions. Basically anything you pass through this test from should be passed through these variables and echoed out.
I'm trying to get this basic method to work so I can implement server side validation and avoid duplicate submissions with the 303 redirect. Please help I've been stuck for days and can't figure out why it only works in chrome.
<?php
session_start();
error_reporting(E_ALL); ini_set('display_errors',1);
if(count($_POST) > 0) {
$_SESSION['testFormText'] = $_POST['testFormText'];
if(isset($_POST['testSubmit'])){
$_SESSION['testSubmit'] = 1;}
header("HTTP/1.1 303 See Other");
header("Location: https://$_SERVER[HTTP_HOST]/test-form/");
die();
}
if (isset($_SESSION['testFormText'])){
$text = $_SESSION['testFormText'];
$submit = $_SESSION['testSubmit'];
/*
Put database-affecting code here.
*/
session_unset();
session_destroy();
}else{
$text = null;
$submit = null;
}
echo '<div class="testForm">
<form method="post" action="">
<input type="text" name="testFormText"/>
<input type="submit" name="testSubmit" value="submit">
</form>
</div>
';
if (!empty($submit)){
echo $text;
}
?>
UPDATE
I've tested different sections of the code using vardumps in an attempt to narrow down the problem, which I believe to be:
header("HTTP/1.1 303 See Other");
header("Location: https://$_SERVER[HTTP_HOST]/test-form/");
die();
From what I've read this is the correct method for a redirect to avoid duplicate submissions. Any idea what's wrong, or can someone please suggest an alternative?
Related
I am getting some information from the login page form.
When I press submit, it goes to a check-login.php page where there it checks from the database if the credentials are correct or wrong.
Then it redirects to a track page.
My problem is that when I press submit on the log in page with the correct credentials.
It redirects to a white page.
And then, if I press refresh, it redirects to the correct page.
<div>
<h1>Login Form</h1>
<form action="check-login.php">
<input type="text" name="user" placeholder="user">
<input type="password" name="password" placeholder="password">
<input type="submit" value="log in">
</form>
</div>
This is the check-login php page
<?php
session_start();
$user=$_GET['user'];
$pass=$_GET['password'];
include("dblogin.php");
$sql="SELECT * FROM login";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if($user==$row["username"] && $pass==$row["password"]){
$_SESSION["userid"]=$row["id"];
header ("Location: tracks.php");
}
}
if ($_SESSION["userid"]==""){
header ('Location: login.html?message=Wrong Username or Password');
}
?>
Try the following code to make a redirect:
http_response_code(302); // send redirect code
header('Location: /tracks.php'); // send Location header
exit(0); // don't send anything else
Try this,
If (!isset($_SESSION['userid'])
{
echo "script type='text/javascript'>window.location.href='login.html?message=Wrong Username or Password'/script";
}
There can be issue due to header function as sometime it doesn't work on some servers.
Note: complete script tag as I'm not able to add code from phone and script tags getting parsed.
I'm not sure this is the issue...
But even if it is not the fix, it can't be a bad thing to do.
Change your form tag like this:
<form action="check-login.php" method="post">
Then in you PHP change it to $_POST variables like this:
$user=$_POST['user'];
$pass=$_POST['password'];
And I strongly suggest again to ugrade your code from mysql to mysqli or prepared statements. There is plenty answers on SO about this.
EDIT
Previous changes I suggested are good.
But wasn't the issue.
An old memory came to me, as I already had a similar problem in the past.
The issue is that your $_SESSION["userid"]=$row["id"]; doesn't have the time to be written before the tracks.php gets accessed.
So do it like this:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if($user==$row["username"] && $pass==$row["password"]){
//$_SESSION["userid"]=$row["id"];
header ("Location: tracks.php?id=" . $row["id"]);
}
}
And in your tracks.php, set it to session.
$_SESSION["userid"]=$_REQUEST["id"];
$_REQUEST will catch $_POST and $_GET.
EDIT: Switch to mysqli
Try this... Even if it is not the fix we're after, it will be a good thing done.
You should apply this modification to all your PHP files.
I know mysql_query has security issues (but not exactly what)... And there may be performance issues too. So it's a good improvement to have at this point.
We'll then be sure the problem source isn't due to this.
<?php
session_start();
$user=$_REQUEST['user'];
$pass=$_REQUEST['password'];
//include("dblogin.php");
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_error()) {
echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
}
$sql="SELECT * FROM login";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$idFound=false;
while ($row = mysqli_fetch_array($result)) {
if($user==$row["username"] && $pass==$row["password"]){
//$_SESSION["userid"]=$row["id"];
$idFound=true;
$idFoundis = $row["id"];
break;
}
}
if ($idFound){
header ("Location: tracks.php?id=" . $idFoundis);
}else{
header ('Location: login.html?message=Wrong Username or Password');
}
?>
I'm having trouble getting a much larger function to post form details in browsers other than chrome. I've narrowed my problem down to my post, redirect, get section of code.
I have recreated the problem with this small function that contains a form and my PRG statement:
function testForm(){
session_start();
error_reporting(E_ALL); ini_set('display_errors',1);
if(count($_POST) > 0) {
$_SESSION['testFormText'] = $_POST['testFormText'];
if(isset($_POST['testSubmit'])){
$_SESSION['testSubmit'] = 1;}
header("HTTP/1.1 303 See Other");
header("Location: https://$_SERVER[HTTP_HOST]/test-form/");
die();
}
elseif (isset($_SESSION['testFormText'])){
$text = $_SESSION['testFormText'];
$submit = $_SESSION['testSubmit'];
/*
Put database-affecting code here.
*/
session_unset();
session_destroy();
}else{
$text = null;
}
echo '<div class="testForm">
<form method="post" action="">
<input type="text" name="testFormText"/>
<input type="submit" name="testSubmit" value="submit">
</form>
</div>
';
echo $text;
}
The function works correctly in chrome. Enter something into the input and submit the form. The data is sent to $_POST then set as a session variable. If the session is set, it is then echoed as the variable $text after the page is redirected back to itself from submitting the form.
This however does not work with firefox and safari. If anyone can suggest how to correctly set the $_POST as a session it would be greatly appreciated.
I am trying to display an error message when there is a username-password mismatch. I set a php session variable if username and password dont match. Then i header back to the same page, with an if conditioned php statement to display an error if the variable is set. But when i unset the variable after error display, there is no error displayed on the page.
I have seen similar problems mentioned in this forum. But i seem to be doing everything right as suggested in questions.. Please help me out...
This is part of my code flow...
<?php
ob_start();
session_start();
.
.
if ($result = $sth->fetch(PDO::FETCH_ASSOC)){
$_SESSION['admin_user'] = $result['id'];
header('Location: admin_user.php');
} else {
$_SESSION['user_found'] = 0;
header('Location: index.php');
}
.
.
//in html body
<?php
if (isset($_SESSION['user_found'])){
if($_SESSION['user_found'] == 0){
?>
<div>
<p class = "bg-danger text-danger">Username Password Mismatch</p>
</div>
<?php
unset($_SESSION['user_found']);
}
}
?>
Now, if unset is removed..it works fine. If it is there, there is no display of error message.
Try not reloading the same page.. remove the header redirect.
if ($result = $sth->fetch(PDO::FETCH_ASSOC)){
$_SESSION['admin_user'] = $result['id'];
header('Location: admin_user.php');
} else {
$_SESSION['user_found'] = 0;
//header('Location: index.php');
}
When I tried the your code, things seem to work fine. Something should be wrong with the code you've not mentioned here..
To troubleshoot the problem instead of
unset($_SESSION['user_found']);
try changing the value of the variable.. say
$_SESSION['user_found'] = -1;
i just created a form and i am facing a problem on submit.
Example:
Here i have the link to edit.php where i get all the information with this link.
index.php
<a href="change/info/edit.php?url= '
. $row['url']
.'&title='. $row['title']
.'&info='. $row['info']
.'&name='. $row['name']
.'&date='. $row['date'] .' " target="_blank">Edit</a>
Here i get all the information from index.php like this here below:
edit.php :
<?php echo $_GET["title"]; ?>
<?php echo $_GET["info"]; ?>
<?php echo $_GET["date"]; ?>
<?php echo $_GET["name"]; ?>
<?php echo $_GET["url"]; ?>
EDIT: Ares Draguna
<?php session_start();
if(isset($_POST['Submit'])){
// code for check server side validation
if(empty($_SESSION['captcha_code'] ) || strcasecmp($_SESSION['captcha_code'], $_POST['captcha_code']) != 0){
$msg='<span class="fail">Please try again.</span>';// Captcha verification is incorrect.
}else{// Captcha verification is Correct. Final Code Execute here!
}
}
But when i hit the submit button and captcha is false the page refresh and i lose all the information, i have to hit back in the browser to see again all the information.
So what do i need to keep the information, when hit the submit button and captcha is false.
Thanks in advance !
To keep the information on the form, you can set some session variables like:
$_SESSION['title'] = $_GET["title"];
$_SESSION['info'] = $_GET["info"];
and so on... and the test it:
if(capcha == false) {
//do something
} else {
//unset the session variables
}
In this scenario, if the capcha is false, then you can repopulate the form inputs with what you have in session, so even after the page is reloaded you still have those information stored. If the capcha is true, then remember to unset the session vars.
However, if the exact same page refreshes, it means that you have the values in $_GET so you could use that with no problems. It really depends on how your code is structured.
L.E:
if(isset($_POST['Submit'])){
$_SESSION['captcha_code'] = $_GET['captcha_code'];
$_SESSION['other_info'] = $_GET['other_info'];
// code for check server side validation
if(empty($_SESSION['captcha_code'] ) || strcasecmp($_SESSION['captcha_code'], $_POST['captcha_code']) != 0){
$msg='<span class="fail">Please try again.</span>';// Captcha verification is incorrect.
}else{
// Captcha verification is Correct. Final Code Execute here!
}
}
And in the view file, check the session variables, so the session vars are set if isset submit post.
Hope it helps!
Keep on coding!
Ares.
I'm submitting a FORM to itself using action="" but what's odd is that my variables are updating after the submission.
<form action="" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit">
</form>
Once this has been submitted and the user successfully logged in, the rest of the page doesn't seem to respond to the updated variables unless I hard refresh.
if ( isset($_POST['found_step_1']) ) {
global $wpdb;
// We shall SQL escape all inputs
$username = $wpdb->escape($_REQUEST['username']);
$password = $wpdb->escape($_REQUEST['password']);
$remember = $wpdb->escape($_REQUEST['rememberme']);
if ($remember) {
$remember = "true";
} else {
$remember = "false";
}
$login_data = array();
$login_data['user_login'] = $username;
$login_data['user_password'] = $password;
$login_data['remember'] = $remember;
$user_verify = wp_signon( $login_data, true );
if ( is_wp_error($user_verify) ) {
echo "Invalid username or password. Please try again!";
$current_step = 1;
} else {
//echo "<script type="text/javascript">window.location='". get_bloginfo('url') ."'</script>";
$current_step = 2;
}
$wpdb->flush();
}
When the page below renders... it's like it's rendering what WAS there before the POST ... the only way to get it to display what the latest data consists of is to hard refresh the page. It's really odd.
EDITED
You need to make the login process one of the first things your script does. I once had similar problems and then found out that I was making the login process too late in my script. I will put a practical pseudo-example that will NOT work as intended:
<?php
if (in_array("Maths",$Subjects) $MainSubject="Maths";
if ($_POST['name'] == "Admin" && $_POST['password'] == "MyCoolPassword!")
{
$Lang=en;
$Subjects = array ("Maths","Physics","English");
}
echo $MainSubject;
?>
This is a too simple code (and will throw some errors), so the mistake is easy to spot. But what if you are working with several includes, calling functions here and there and doing many things like this? Then the same mistake could occur at a large scale. Just one thought, but without more code from the OP we cannot really answer, just give some 'maybe it's this'.
Other thing that could go wrong is that cookies are set AFTER finishing parsing the php code, not at the instant that setcookie() is called in the code. A more throughout answer can be found here: php set cookie issue
what's odd is that my variables are updating after the submission. I guess you mean your variables are NOT updating right after the submission from the rest of the question, it's pretty unclear. Please post more code so we can help you better.