Why POST['submit'] is set when I reload? - php

My application is a simple login page. When it fails, I print an error message. My question is, why when I reload the page the message is been printed again? How can I fix that?
The code is working fine, I've made another php file executing the database check & connection.
<?php
require_once("include/database.php");
if(isset($_POST['submit'])) {
connect_bookstore(); // custom function
$spassword = sha1($_POST['password']);
$username = $_POST['username'];
if ( checkpassword($username,$spassword) ) { //custom function
header('Location:insert.php');
exit;
} else {
$message = "Login failed!";
}
}
?>
Inside the html body.
<?php
if (isset($message)) {
echo $message;
}
?>

<?php
session_start();
require_once("include/database.php");
if(isset($_POST['submit'])) {
connect_bookstore(); // custom function
$spassword = sha1($_POST['password']);
$username = $_POST['username'];
if ( checkpassword($username,$spassword) ) { //custom function
header('Location:insert.php');
exit;
} else {
$_SESSION['message'] = "Login failed!";
header('location: /yourfile.php');
exit;
}
}
if(isset($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
?>
Fundamentally, yes, post/redirect/get... but sometimes a simple explanation is better.
I use sessions to store flash messages, then display them like this.

Thats because you are resending the same POST data when you refresh, if you do a GET request you will notice in the URL your parameters that you are passing are there, so if you refresh those parameters are once again sent. Same thing with POST.

When you reload the page, the browser will send the same request that it sent for theoriginal page.
You want a POST-Redirect-GET.

Related

Session variable appears empty on different page

Edit: after doing some trial and error stuff I notice that if I comment the following code:
$success = $_SESSION["success"];
session_unset($_SESSION["success"]);
the $to variable displays as intended. So my question is why can't both be at the same time used?
Original question:
I'm trying to send an email using the mail() function. In order to do that I pass the variable $_SESSION['emailfrompass'] across 2 pages but for some reason the variable is always empty. Even though there is another variable that I send with a message and I have no problems in receiving it, this is the only one that makes problems
The session_start() is set across all pages. I tried using
ini_set('display_errors',1);
error_reporting(E_ALL);
for finding the problem but no use. The variable is always empty
This is my enterEFPass.php file. On top I have
<?php
session_start();
ini_set('display_errors',1);
error_reporting(E_ALL);
?>
<?php
if(isset($_SESSION["success"]))
{
$success = $_SESSION["success"];
session_unset($_SESSION["success"]); //echoing this will display the right thing
$to = "";
$to = isset($_SESSION['emailforpass']) ? $_SESSION['emailforpass'] : 'not found';
echo $to; //does not work
//mail($to, "Reset your password", $message, $headers);
?>
<div id='alert'>
<div class='alert alert-block alert-info'>
<?php
echo $success;
// echo "<script>setTimeout(\"location.href = 'login-page.php';\",2500);</script>";
?>
</div>
</div>
<?php
}?>
And this is the enterEFPass_route.php in which I instantiate the $_SESSION variables
<?php
session_start();
include 'db.php';
$email = "";
$conn = Connect();
if (isset($_POST['send_email_button']))
{
$email = mysqli_real_escape_string($conn, $_POST['email']); //$_POST['email'] the field where I introduce the email
}
if (empty($email)) { array_push($errors, "Please enter a valid email"); }
if (count($errors)==0) // just an array for error messages
{
$_SESSION['emailforpass'] = $email; //appears empty always
$_SESSION['success'] = "An email has been sent to the corresponding address. Please follow the instructions provided there"; //goes without problems
header("location: enterEFPass.php");
} else
{
$_SESSION['errormsgpassress']= $errors; //no problems in sending
header("location: enterEFPass.php");
}
}
?>
I expect the $to variable to print on the screen but it always prints "not found"
If I print $_SESSION['success'] there is no problems in that
The method session_unset() does not take any arguments. It is used to unset ALL session variables, thus it is unsetting the $_SESSION['success'] variable. See here for more details on that. Instead, use unset($_SESSION['success']); to unset a single session variable. Hope this helps!

PHP Coding Logic

I have some code that always is returning $aid=1 within an else/if statement. Can anyone help me figure out why this may be happening within the logic?
<?php
session_start();
require('includes/config.php');
if(!$user->is_logged_in()){ header('Location: login.php'); }
include_once("config.php");
if(isset($_SESSION['account_id'])) {
$aid = $_SESSION['account_id'];
} else if(isset($_POST['aid'])) {
$aid = $_POST['aid'];
} else if(isset($_GET['aid'])) {
$aid = $_GET['aid'];
} else {$aid='1';}
include_once('includes/top.php');?>
Quick background (if it helps)... This is for a login. Once a client signs in I am trying to get only their data within the database to show. I have all of the correct data being pulled, but I cannot get the logged in user to call in the correct account_id. If I were to change the last $aid=1 to $aid=2, then it would correctly pull all of account_id=2 information, but it would do it for every logged in person.
Any advice is greatly appreciated.
Thanks!
Below is the login function
<?php
require_once('includes/config.php');
if( $user->is_logged_in() ){ header('Location: main.php'); }
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: main.php');
exit;
} else {
$error[] = 'Invalid username/password or your account has not been activated.';
}
}
$title = 'Login';
require('layout/header.php');
?>
There is some html below the php that calls in the form. I can load that up if that helps too. Thanks!
Also, the account_id's are managed within the admin section. There is an associated account_id within the clients table of the database that specifies which account each user has.
If else condition page your are not post and get any data's so post and get method will not work. Then u need to make sure session is set or not. After that only u can able to find out the exact value of $aid.

PHP Session Works Slowly

I've started to learn PHP Sessions recently.That really helped me to do the login properly.
I should give the link to you first: mk-appform.net16.net/login.php(feel free to use as you want,This is a testing.Im able to change the pass as soon as it gets fixed)
Username:admin
Password:1234
Please test it
The problem is,When you're not logged in and type mk-appform.net16.net/advsearch.php directly in the adress bar,The content of the page that I require login beforehand is visible for a second.Then it redirects to login page.But you know,I would not want this to be shown in any way.It should require login eventually.
Here are the PHP codes of login.php
<?php
if (isset($_POST['submit']))
{
if(isset($_POST['user']) && isset($_POST['password']))
{
$user = $_POST['user'];
$password = $_POST['password'];
if(empty($user) || empty($password))
{
echo 'Please fill the form';
}
else
{
if($user == 'admin' && $password == '1234')
{ // check the infos
session_start();
$_SESSION['user'] = 'admin';
$_SESSION['password'] = '1234';
echo 'Login Succeeded.Now redirecting to panel...';
header("refresh:2; url=advsearch.php");
}
else
{
echo 'Invalid Username or Password';
}
}
}
else
{
echo 'Please use the form';
}
}
?>
And ,the code of the content I show after successfully logging in(advsearch.php)
<?php
session_start();
if(isset($_SESSION['user']) && isset($_SESSION['password']))
{
if($_SESSION['user'] == 'admin' && $_SESSION['password'] == '1234')
{
header("url=advsearch.php");
}
else
{
session_destroy();
echo 'Redirecting..';
}
}
else
{
header("refresh:0; url=login.php");
}
?>
header redirects aren't instantaneous. It takes a few moments for the browser to start shutting down the connection and initiate the new one. That means any content you output on the page after you output the location header can still be viewed. You have to abort your script after outputting the header. e.g.
<?php
if (need to redirect) {
header('Location: login.php');
echo 'redirecting to login page, please wait ...';
exit(); // you need this
}
... regular page contents ...
In short, if you don't want something visible to the user, then DON'T output it in the first place. Don't depend on everything working properly (or even fast). They rarely do.

Session fails to maintain after page redirect

I have been beating my my head over this. My code is virtually identical to other projects where this DOES work. Here is how I do it:
session_start();
set_up_session($username);
redirect_to('index.php');
And the two functions:
function redirect_to($location=null) {
if($location!=null) {
header("Location: {$location}");
exit;
}
}
function set_up_session($username) {
session_start();
$_SESSION['user_id']=$id;
$_SESSION['logged_in']=true;
$_SESSION['username']=$username;
}
if I comment out the redirect and echo any of the $_SESSION var's, the var reads correctly. But after the redirect, the session ends.
This is what's on the next page.
<?php if (!isset($_SESSION['logged_in'])) { ?>
// do stuff <-- this is what gets shown showing session is no longer active
<?php } else { ?>
<p>Hi, <?php echo $_SESSION['username']; ?></p>
<?php } ?>
make sure the page you are redirecting to has session_start() at the top of the document
if(!isset($_SESSION)){
session_start();
}
My first step I would do is try this on the next page:
<?php
if (isset($_SESSION['logged_in'])) {
echo $_SESSION['username'];
} else {
//do stuff
}
?>
I had a problem a posted earlier in dealing with sessions. My resolution to the problem was to set a $_SESSION[]; to a variable. EX:
<?php
$Username = "Guest"; //Set your variable before you actually need it. (This is what fixed my problem)
if (isset($_SESSION['logged_in'])) {
$Username = $_SESSION['username'];
}
?>
NOTE: You might want to change the if (isset($_SESSION['logged_in'])) to instead check for if the username is set. For example:
<?php
$User = "Guest";
if (isset($_SESSION['username'])) {
$User = $_SESSION['username'];
} else {
//do stuff
}
?>
Also, as stated by the other user, make sure the page you redirect to has a session_start(); function in it. Otherwise, this will not work.

Losing session values after header redirection

I'm using $_SESSION to keep my users logged in after they have logged in.
When they return to the homepage, they at first appear to be logged in, but after refreshing the page once, they are no longer logged in.
NOTE: I'm still learning PHP programming so please don't mind that most of my code is rather, noobish.
Index.php Code:
<?php
session_start();
$UserOnline = "Guest";
if (isset($_SESSION['username'])) {
$UserOnline = $_SESSION['username'];
}
echo $UserOnline;
?>
Login.php Code:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username)) {
$InvalidLogin = "Please submit a username";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
} elseif (empty($username)) {
$InvalidLogin = "Please submit a password";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
require 'required/connect.php';
$result = mysqli_query($con, "SELECT * FROM users WHERE username='$username'");
$row = mysqli_fetch_array($result);
if ($password == $row['password']) {
$_SESSION['username'] = $username;
echo "Successful Login!";
echo "<br>";
echo "<a href='index.php'>Return to HomePage?</a>";
} else {
$InvalidLogin = "Your info didn't match ours!";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
?>
I have tested on the login.php page if the user is in a session there, and I always get the correct return value. The issue is that after I refresh once on the Index.php page, the user is no longer in a session.
Is there something I'm forgetting, or am I not using the $_SESSION correctly? Is there another error that I simply do not know about?
Put exit; after header('location:.....') and your problem will be solved.
Issue is resolved. Error was found in Index.php. Set Variable $UserOnline before the if(isset($_SESSION['username'])). Thanks for the help guys

Categories