Two HTML forms submitted by PHP trigger each other - php

i've got 2 forms on one page, but when I press submit one the other is actioned.
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit" name="getNameSubmit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
if(isset($_REQUEST['fname']) && $_REQUEST['fname']!="")
{
$name = htmlspecialchars($_REQUEST['fname']);
if (empty($name)) {
echo "Hello dear user.";
} else {
echo "Hello $name";
}
}
}
?>
and
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Full text: <input type="text" name="stringtoreplace" value="">
Word(s) to change: <input type="text" name="wordstochange" value="">
Change to: <input type="text" name="wordstoinput" value="">
<input type="submit" name="wordReplaceSubmit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field -- the if(isset) stops a pre-comparison that throws an E_NOTICE level error
if(isset($_REQUEST['stringtoreplace']) && $_REQUEST['stringtoreplace']!="")
{
$stringoutput = htmlspecialchars($_REQUEST['stringtoreplace']);
}
if(isset($_REQUEST['wordstochange']) && $_REQUEST['wordstochange']!="")
{
$tochange = htmlspecialchars($_REQUEST['wordstochange']);
}
if(isset($_REQUEST['wordstoinput']) && $_REQUEST['wordstoinput']!="")
{
$changeto = htmlspecialchars($_REQUEST['wordstoinput']);
}
if (empty($stringoutput)) {
echo "Please enter your text and the words to change.";
} else {
echo str_replace($tochange, $changeto, $stringoutput);
}
}
?>
How can I get one to action without triggering the other? The function and placement isn't a factor here, I'm just doing some practice, but would be nice ton understand why this happens and how to resolve.

<?php echo $_SERVER['PHP_SELF'];?> gives the current URL, so because they're in the same page, it causes the problem. You can check this on inspecting the page Ctrl + Shift + i then clicking on Elements on Chrome.
One solution might be to give different URLs to both the forms or use parameters on post request. Eg.- <?php echo $_SERVER['PHP_SELF'].'?form=form1';?> & <?php echo $_SERVER['PHP_SELF'].'?form=form2';?>
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_GET['form'])){
if($_GET['form'] == 'form1'){
//code for form1
}else{
//code for form2
}
}
}

Ok, let's start on why this is happening.
The action parameter of an HTML tells the browser which URL to send the POST request with the form data. In your case, it's $_SERVER['PHP_SELF'], which is the current PHP script. You use the same for both forms.
When one of the forms is submitted, your PHP script gets called, and all the PHP in the script gets executed. The first part (the one after the first form) checks if ($_SERVER["REQUEST_METHOD"] == "POST"), decides that yes, it was a POST request, and tries to proceed. After that, the second part (the one after the second form), uses the exact same check, decides that yes, it was a POST request, and tries to proceed too.
Ideally, it would be cleaner to have two different pages to process two different forms; but if you prefer to keep all in the same page, you have a couple of different options to distinguish between the two.
1) Use a different query parameter in the action attribute for each form, as suggested by #sauhardnc. The forms would look like:
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?form=form1">
...
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?form=form2">
while the PHP side would do something like
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_GET['form'] == 'form1') {
// code for form1
} else {
// code for form2
}
}
2) Use a different input in each form. The forms would look like:
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
...
<input type="hidden" name="form" value="form1">
</form>
...
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
...
<input type="hidden" name="form" value="form2">
</form>
while the PHP side would do something like
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_REQUEST['form'] == 'form1') {
// code for form1
} else {
// code for form2
}
}

Related

How to show value of input in PHP?

I have this input field in a form:
<form method="post" class="tester" enctype="multipart/form-data" action="#">
<input type="number" name="test">
</form>
Whenever I try to get the input / value of the input data, filled in by my users, I can not show it (it just does not echo it). This is the code I use to echo it:
<?php
$well = $_POST['test'];
echo $well;
?>
I tried using GET as well, but nothing works.
var_dump gives me:
array(0) { }
Can you help?
Your form do not seem to have any issue even after using hash# it still process the form. Also your PHP code it's fine.
index.php
<form method="post" class="tester" enctype="multipart/form-data" action="#">
<input type="number" name="test">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$well = $_POST['test'];
echo $well;
//print_r($_POST);
}

html form: prevent re-submitting while sending

I have this form:
<form action="" method="post" name="my_form">
<input type="text" name="my_input">
</form>
You can write some text and the submit by pressing the enter key.
My problem: When you press the enter key multiple times, it'll also sent multiple times to my server.
There are solution like this:
onsubmit="my_button=true;return true;"
But these solutions require a submit button.
Is there a way to do this without adding a (hidden) submit button?
If you want to be absolutely sure, for example, submitting the form twice can cause severe damage/cause malicious things to happen, then you need to check this serverside. One rule of webdevelopment and general development is to never trust your end-user, and by simply blocking the form using JavaScript, you cannot be assured that a malicious user won't be sending the form twice by getting around the JavaScript.
What you can do is something like this:
Important: This is just a proof of concept example to explain the idea, this is not a 100% bulletproof solution.
Form
<?php
session_start();
$_SESSION['nonce'] = random_number();
?>
<html>
...
<form method="post" action="process.php">
<input type="hidden" name="nonce" value="<?php echo $_SESSION['nonce']; ?>" />
... other form elements ...
</form>
...
process.php
<?php
session_start();
$nonce = isset($_POST['nonce']) ? (int)$_POST['nonce'] : 0;
$session_nonce = $_SESSION['nonce'];
if ($_SESSION['nonce'] != $nonce) {
die("Invalid nonce, double submission detected.");
}
$_SESSION['nonce'] += 1; // this will cause the previous check to fail on a second submission.
some like this :
<form onsubmit="send();" method="post" name="my_form">
<input type="submit" name="my_input" id="sub">
</form>
js code:
function send(){
$("#sub").attr('disabled', 'disabled');
$.ajax({
// data
success: function(data){
$("#sub").attr('disabled', false);
}
});
}
Like this (untestet):
var formSubmitted = false;
document.getElementById('my-form').addEventListener('submit', function(){
if(formSubmitted === false) {
formSubmitted = true;
return true;
}
return false;
});
You could disable the button once it's set so the User cannot click it again
<form action="" method="post" name="my_form">
<input type="text" name="my_input" <?php if(isset($_POST['my_input'])) { print
'disabled'; } ?>>
</form>

php prevent form resubmission using sessions

So I am trying to prevent form resubmission using sessions
and this is my code :
<?php
session_start();
if(isset($_GET['unid']))
{
if ($_GET['unid']==$_SESSION["uid"])
{
echo "Form is Submited do something";
}
else
{
echo "no you can't do that";
}
}
$unid = md5(uniqid());
$_SESSION["uid"] = $unid;
?>
<form method="GET">
<input name="name" value="test">
<input name="unid" value="<?php echo $unid;?>">
<input type="submit">
and it works ...but if the user opens another tab then it will break so how can I fix it ?
I'm not sure about this but may be assigning a new global session variable will work, say $_SESSION['checkSub']. So once the form is submitted, set it to 1 or true and only let form submission if it isn't 1 or false.
You can check to see if the unid is set in the session before generating a new unique id. See updated code below:
<?php
session_start();
if(isset($_GET['unid']))
{
if (isset($_SESSION['unid']) && $_GET['unid']==$_SESSION['unid'])
{
//form has been submitted with matching unid - process it as needed
unset($_SESSION['unid']);
}
else
{
// Form was resubmitted or some other logic error
}
}
$unid = ''; //declare here for good scope
if (isset($_SESSION["unid"])) {
$unid = $_SESSION["unid"];
}
else {
$unid = md5(uniqid());
$_SESSION["unid"] = $unid;
}
?>
<form method="GET">
<input name="name" value="test">
<input name="unid" value="<?php echo $unid;?>">
<input type="submit">
Rather than using form method GET, try to use POST. It will work for you. The $_POST array will only have data in it when form is submitted, so you should not have to use the session to know whether form is submitted or not.

php double form submit prevent

I would like to avoid the double form submit or unwanted submit when first time clicking the link to the form which outputs empty data.
The code I managed to find there , seems to prevent double or single empty form or previous form submit but it also prevents to submit the form when expected.
Main parts of the code as below, all parts on the same php file.
<?php
session_start();
$_SESSION['token'] = md5(session_id() . time());
?>
<!DOCTYPE HTML>
...
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>" name="form_submitted">
<input type="hidden" name="token" value="<?php echo $_SESSION['token'] ?>" >
<input type="checkbox" name="catexp[]" value="1">Input1
<input type="checkbox" name="catexp[]" value="2">Input2
<input type="checkbox" name="catexp[]" value="3">Input3
<input type="Submit" name="Submit" >
</form>
<?php
if (isset($_SESSION['token']))
{
if (isset($_POST['token']))
{
if ($_POST['token'] != $_SESSION['token'])
{
// double submit
}
else
{
// FORM PROCESSING HERE
}// else ($_POST['token'] == $_SESSION['token'])
} // if (isset($_POST['token']))
} // if (isset($_SESSION['token']))
?>
What needs to be done to make the form processing in the condition run?
Tkanks
Pascal
Setup session ID with user
Check if session ID is already in the database
Insert form if session is unique to database
I would recommend using a client-side check to reduce work required by the server. Use some JavaScript for this.
When first time form is submitted simply clear the $_SESSION['token']
if (isset($_SESSION['token']))
{
if (isset($_POST['token']))
{
if ($_POST['token'] == $_SESSION['token'])
{
unset($_SESSION['token']);
// do form processing
}
else
{
// double submit

php two self submitting forms on one page

I have a webpage form that submits to itself to carry out php action. I want to add a second form to this same webpage that is capable of self submit as well but I am not having any luck finding a working solution for my setup. Here is what my webpage looks like.
First, it checks to see if the page has already been submitted, and if it has, it redirects elsewhere.
if($_SERVER['REQUEST_METHOD'] == "POST") {
header("Location: viewcustomers.php");
}
Next, the form itself.
<form id="addCustomer" method="POST" action=""> ..stuff.. </form>
Then, finally my form action.
if('POST' == $_SERVER['REQUEST_METHOD']) {
..phpstuff..
}
How could I adjust this form action (or add another) to differentiate between two different forms?
Thanks.
Easy!
<?php
if(isset($_POST['action']) && $_POST['action'] == 'form1') {
// Form 1
} else if(isset($_POST['action']) && $_POST['action'] == 'form2') {
// Form 2
}
?>
<form action="#" method="post">
<input type="hidden" name="action" value="form1" />
</form>
<form action="#" method="post">
<input type="hidden" name="action" value="form2" />
</form>

Categories