I am trying to come up with a method to differentiate between form being submitted by a unique POST value. While in and of itself this is not that complex an issue my circumstances can lead to their being an issue.
while(!isset($_SESSION['user']) || empty($_SESSION['user'])){
require_once('login_form.php');
}
When a user goes to a page that requires the user to be logged in to view it. If someone lands on one of these pages and is not already logged in I am displaying the login form. The login form's action is itself, or rather the page being displayed. Now my issue comes when the page being displayed also has a form. I need a method to ensure that the $_POST data from the login form does not make it to the $_POST data from the page's form. Normally it would not be an issue except when when form inputs share the same name.
I am wanting a way to differentiate between forms using some unique value. I had been thinking about using HTML buttons for submission.
while(!isset($_SESSION['user']) || empty($_SESSION['user'])){
require_once('login_form.php');
}
if(isset($_POST['PAGE_FORM']) && !empty(PAGE_FORM)){
unset($_POST);
}
<form name="PAGE_FORM">
<button valuye="PAGE_FORM">Submit</button>
</form>
I had also thought about doing something like this instead.
while(!isset($_SESSION['user']) || empty($_SESSION['user'])){
require_once('login_form.php');
if(isset($_SESSION['user']) && !empty($_SESSION['user'])){
unset($_POST);
}
}
<form name="PAGE_FORM">
<button valuye="PAGE_FORM">Submit</button>
</form>
Let me know what you think. I would be interested in any other ideas you might have.
Instead of including the login_form, do a http redirect to a seperate login form.
Related
This question already has answers here:
Avoid resending forms on php pages
(6 answers)
Closed 9 years ago.
I have a webpage that contains a form that uses the POST method and references the same page it is on for submission. I am using a PHP include file that contains an if statement that runs when the submit value is set. For some reason though, after one submission, every time you refresh the page it submits the form with the previously submitted data (The browser warns of this before refreshing the page). What causes this, and what could I be doing wrong?
This is expected. You should have the form submit to a handler that has a unique URL, whether it be a query string or a different URI. One solution (of many) would be to change your form action:
<form action="?action=submit" method="post">
<input type="hidden" name="action" value="submit" />
...
and then in the PHP script handle the form, then change the context back to a URL without the hidden query string
if (!empty($_POST['action']) && $_POST['action'] == 'submit') {
// do stuff
header('Location: '.$_SERVER['SCRIPT_NAME']);
die();
}
Note the query string is not actually present in $_POST but we keep it there so browsers don't consider it to be a redirect loop.
i had the same issue with one of my pages.
the reason is that when the browser warns you that it will submit the form again, that means it is going yo be the same exact thing when you click on a submit button.
I did 2 things to avoid it but i am sure there many other ways.
1. Do not let the page echo the form again after succesfull submission of the form.
mine was like this
<?php
if(!isset($_POST['submit'])) {
include(form.php);// you can modify this according to your needs.
} else {
//display your message about what happened with the form.
}
?>
with that approach, your page will not the contaion a form to submit HOWEVER this will not prevent it from submitting on refresh.
2. if the form is submitted create a contoller input that carries a value indication that the form is already submitted. for example , place this into your form:
<?=(isset($_POST['submit']))?"" :"<input type-"hidden" name="submit_stat" value="true" />" ; ?>
and when you process your form when it is submitted check it with your php and make the script act on that variable like this:
<?php
if($_POST['submit_stat']==true) {
//do not process the form here.
//stop your script
}
?>
Another thing you can do is redirect your page to another page other than the page that handles the form. i believe this is the safest one.
Another Way to prevent this is to move the Post Data to Session, redirect, collect Post back from Session and delete Session Post Data.
if(!empty($_POST) && empty($_FILES)){
// move post to session
// redirect to same url (don't forget possible get query)
}else{
// collect post from session
// unset post from session
}
Build this as default and you should never have problems with post data.
Only exceptions are File uploads. In this case redirect *after* post processing manualy.
I have some information which gets passed from a form and needs to be used once and only once. I can collect it nicely from $_POST but I'm not sure which is the "best" way to ensure that I can only use it once, i.e. I want to avoid the user pressing F5 repeatedly and accessing the function more than once.
My initial thought was to set a session variable and time the function out for a set period of time. The problem with that is thay could have access to the function again after the set period has elapsed.
Better ideas welcomed!
A redirect to another page would be sufficient to break most browser repost-on-refresh behaviour. Setting a cookie on form submit (or a session variable, as you suggest) would also work quite nicely. You could have the form submission page unset the session variable again, such that only a fresh access to the form would permit re-submitting the form.
This one's VERY easy to implement.
All you need to do is this:
have your form submit to a different page, which will only handle the post information, and not display ANYTHING
Then, send a LOCATION header to redirect the browser to a new page (which will be retreived by GET) This will break the browser's repost-on-refresh behaviour
You can redirect to some other page, like doing
header("Location: index.php");
How about:
1) create a page with the form, eg myformpage.php
2) Make the action of the form myformpage_submit.php
3) in myformpage_submit.php do whatever it is you need to do with the posted info, like inserting into a database.
4) When finished, direct the browser to another page, eg nicework.php
This should dispose of them as you wish.
To avoid the user refreshing the page and accessing to the information,
You can use the token method in the form like this:
<?php
if ( isset($_POST['submit'], $_POST['token']) && ($_POST['token'] === $_SESSION['token']) )
{
// do something here
}
$_SESSION['token'] = uniqid();
?>
And for the form
<form method="POST">
<input type="hidden" name="token" value="<?= $_SESSION['token'] ?>">
<button name="submit" class="btn btn-success">Submit</button>
</form>
I am currently doing a web application project for my final year in school. I am more of a web designer than a web developer so I need as much help as I can get!
For my project, I am create a website very similar to a blogging site.
The first function I wanted to implement runs when the user is registering, I wanted signUp.php(html form) / doSignUp.php(php post data to database) to prevent the user from using a username that is already in the database.
For example, database has username="happy". User1 fill up the form at
signUp.php in the username fill "happy" and submit the form into
doSignUp.php. doSignUp.php checks the database whether
username="happy" is inside. If it is inside, it will NOT post the data
again inside to prevent double entry but instead REDIRECT back to
signUp.php and inform the user that with a message "the user name is
in used".
For the first function I have the idea of:
$selectUser = executeSelectQuery("SELECT username FROM user WHERE username="$username")
if ($selectUser==0) {
$doRegister = executeInsertQuery("INSERT INTO user (Name,Username, Email,
Password, DOB_Date, DOB_Month, DOB_Year, Gender,admin, Country) VALUES
('$Name','$Username','$Email',SHA1('$Password'),'$DOB1','$DOB2','$DOB3','$Gender','$role' ,
'$Country')");
} else {
<// redirect codes here to signUp.php with message "user name is in used">
}
Second function I want to implement involves login.php(login form), doLogin.php(check whether the posted data matches with the one entered in the login form) and memberPage.php(redirect the user to memberPage if he is the member and create a session for him, else redirect to login.php if he is not a member to show him some message).
As for the second function, I have really no idea how to implement the post-redirect-get method for my login. I tried google for demos to try but to no avail. Please help if you can! Thanks in advance :D
Code to redirect:
header("Location: signUp.php?message=" . urlencode("user name is in use"));
In signUp.php, to print the error, print $_GET['message'].
In your case, using the header() function to redirect back to your sign-up display page (signUp.php) with a message will work, however I often discourage this multi-file attempt at form processing.
Something much more appealing (at least to me) is placing the processing logic at the top of the file that displays the form. This logic would need to be wrapping in a check to make sure the form had been submitted. If anything goes wrong, it stores the error in a variable that could be displayed later in the file. Take a look at this example:
<?php
if($_POST['submit'] == 'Submit') {
if(!$userNameIsUnique) { //Mysql Processing - duplicate check here
$message = "Username has already been used.";
}
//Check other fields for duplicates or invalid data
if(!isset($message)) {
//Form submit successful send info to data
mail(); //Send confirmation email
die('Check your email to verify your account!'); //Display success message
}
}
?>
<html>
<head><title>Signup</title></head>
<body>
<?php if(isset($message)) echo '<p>'.$message.'</p>'; ?>
<form action="" method="post">
<input name="username" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
In this situation, you can still separate views and controller logic (with file includes), but you avoid having two files and forcing two requests (one for the form submit and one to redirect back to the form) when there is an error with the input.
Say I have create a registration form. Now to add records into a DB, we send the data to another php file by POST method, where we do some validations and add a record. Is it possible to do it in the same file without sending and getting the data by POST/GET? If no, then why?
EDIT: Even sending to the same php file is SENDING and losing resource. I ask this question because I want to avoid the lost of time on sending by GET/POST and getting by the same Get/POST. And if it is not posible, I want to understand why PHP does not allow.
No. You always have to send data from the client to the server, there is no way around that.
If you dont want to reload the entire page the user is on, you could submit the data via AJAX to the php file responsible for processing it and adding the data. That way the user never leaves the page.
yes ofcourse.
just in your form "action" put
$_SERVER['PHP_SELF']
then in the beginning of your PHP page check if the $_POST is set or not
if(isset($_POST))
{
// actions to be taken after form submission
}
ofcourse you can add a hidden input tag for refining checks for the $_POST. eg in your form
<input type="hidden" name="formSubmit" value="yes" />
then your check should be like
if(isset($_POST['formSubmit']))
{
// actions to be taken after form submission
}
It's possible. For example:
<?php
if(true === isset($_POST['submit']) // check if submit-button was clicked
{
// do some validation here...
// If validation successes add record into db here...
}
else // no post data sent so output the form
{
// output the form here...
}
Yes it is possible set
action="same page"
in form tag.
you can access your all form attributes on same page.
Yes it is easy. The form can post back to its self. This is most easily done by not even specifying the value of action in the form tag.
<form method='POST'>
Then at the top of the page before any content is put on the page, include an if statement to check if the form was submitted.
if (isset ($_POST['post'])) { // 'post' is the name of the submit button
$error = false;
// Do validation
From there do validation and act according to the result.
If you have lots of validation to do, perhaps put that in another file and include it.
include "formValidation.php";
If all is well and all tests are passed use
if ($error === false) {
Header ("Location: confirmation.php");
exit;
}
}
If tests fail, stay on the page keeping all the post data, and display an error.
if (isset ($error) && !empty ($error)) {
echo "<div class='error'>$error</div>";
}
I have an HTML form. Let's say I fill out all the fields and submit it (PHP script runs here).
Then I want to go back to the form using "Back" button of my browser.
What I see is the empty form.
What do I do to have the entered data retain on the page after I come back to it using "Back" button of the browser?
Thank you!
If you use the "Back" button of your browser then your browser is responsible for re-populating your form data.
Usually that functionality is handled by the browser, however if you want to "force" the fields to always be pre-filled with the user's data, you can store the $_POST data in a session variable and use that to load the form.
Example:
// submission page
session_start();
if(isset($_POST)){
// save the posted data in the session
$_SESSION["POST"] = $_POST;
}
Then on the actual form page, you can check to see if session data exists. It won't if the form is being loaded the first time, but it will if the user submits the form and then presses the browser back button:
// form page
session_start();
if(isset($_SESSION["POST"])){
// previous POST data has been saved
// build the form with pre-defined values from $_SESSION
...
} else {
// no previous data
// build the form without pre-defined values
...
}
Note that you must call session_start() before outputting any HTML.
Store the value in a session
session_start();
//form so that you have all the potential forms in a single session array
//form_1 to identify the form in question
if(!empty($_POST)){
$_SESSION['forms']['form_1'] = $_POST;//if this is for the public internet, then I would really consider making sure that the posted data matches the received data... (and that its comming from YOUR form), which is way too long to post here...
}
then on the form page
<input name="flowers" value="<?php echo if(isset($_SESSION['forms']['forms_1']['flowers'])){ echo htmlspecialchars($_SESSION['forms']['forms_1']['flowers']);} ?>" />
obviously the above can be simplified, but for a example's sake it's better this way.
(make sure to clean out the old form data eventually)
You can potentially store the data in the session, and re-populate it back using PHP sessions. You should create a separate back button that takes you to the previous page.
Example:
Storing data:
$_SESSION['data'] = $_POST['item1'];
In the HTML Forms:
<input type="text" name="someinput" value="<?=$_SESSION['data']?>" />