I am stuck and hoping someone can help.
I am trying to get the user's input (their $name) to show in the $alert'' when user submit form. Example: User types in to the form the following: ** Name: Joe , Tel: XXX.XXX.XXXX , Email: Joe#example.com *** and pushes submit.
-- page refreshes and says. "Message sent Joe, thank you for contacting us!"
$mail->send();
$alert = <div class="alert-success">'
<span>Message sent $name, thank you for contacting us!</span>
</div>';
You need to fix your typos, like this:
$mail->send();
$alert = '<div class="alert-success">'.
'<span>Message sent '.$name.', thank you for contacting us!</span>'.
.'</div>';
Now that you have a template in $alert you will need to make sure that you display it. The simplest way to do so is to echo it, like
echo $alert;
But you may need to display it somewhere else than the current position. Also, PHP is a template language as well, so in some environments you can do something like
$mail->send(); ?>
<div class="alert-success">
<span>Message sent <?php echo $name; ?>, thank you for contacting us!</span>
</div>
<?php
I think that this problem occurs often on a web application development. But I'll try to explain in details my problem.
I'd like to know how to correct this behavior, for example, when I have a block of code like this :
<?
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
echo "Operation Done";
die();
}
?>
<form action='page.php' method='post' name="myForm">
<input type="text" maxlength="50" name="name" class="input400" />
<input type="submit" name="Submit" />
</form>
When the form gets submitted, the data get inserted into the database, and the message Operation Done is produced. Then, if I refreshed the page, the data would get inserted into the database again.
How this problem can be avoided? Any suggestion will be appreciated :)
Don't show the response after your create action; redirect to another page after the action completes instead. If someone refreshes, they're refreshing the GET requested page you redirected to.
// submit
// set success flash message (you are using a framework, right?)
header('Location: /path/to/record');
exit;
Set a random number in a session when the form is displayed, and also put that number in a hidden field. If the posted number and the session number match, delete the session, run the query; if they don't, redisplay the form, and generate a new session number. This is the basic idea of XSRF tokens, you can read more about them, and their uses for security here: http://en.wikipedia.org/wiki/Cross-site_request_forgery
Here is an example:
<?php
session_start();
if (isset($_POST['formid']) && isset($_SESSION['formid']) && $_POST["formid"] == $_SESSION["formid"])
{
$_SESSION["formid"] = '';
echo 'Process form';
}
else
{
$_SESSION["formid"] = md5(rand(0,10000000));
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="hidden" name="formid" value="<?php echo htmlspecialchars($_SESSION["formid"]); ?>" />
<input type="submit" name="submit" />
</form>
<?php } ?>
I ran into a similar problem. I need to show the user the result of the POST. I don't want to use sessions and I don't want to redirect with the result in the URL (it's kinda secure, I don't want it accidentally bookmarked). I found a pretty simple solution that should work for the cases mentioned in other answers.
On successfully submitting the form, include this bit of Javascript on the page:
<script>history.pushState({}, "", "")</script>
It pushes the current URL onto the history stack. Since this is a new item in history, refreshing won't re-POST.
UPDATE: This doesn't work in Safari. It's a known bug. But since it was originally reported in 2017, it may not be fixed soon. I've tried a few things (replaceState, etc), but haven't found a workaround in Safari. Here are some pertinent links regarding the issue:
Safari send POST request when refresh after pushState/replaceState
https://bugs.webkit.org/show_bug.cgi?id=202963
https://github.com/aurelia/history-browser/issues/34
Like this:
<?php
if(isset($_POST['uniqid']) AND $_POST['uniqid'] == $_SESSION['uniqid']){
// can't submit again
}
else{
// submit!
$_SESSION['uniqid'] = $_POST['uniqid'];
}
?>
<form action="page.php" method="post" name="myForm">
<input type="hidden" name="uniqid" value="<?php echo uniqid();?>" />
<!-- the rest of the fields here -->
</form>
I think it is simpler,
page.php
<?php
session_start();
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
$_SESSION["message"]="Operation Done";
header("Location:page.php");
exit;
}
?>
<html>
<body>
<div style='some styles'>
<?php
//message here
echo $_SESSION["message"];
?>
</div>
<form action='page.php' method='post'>
<!--elements-->
</form>
</body>
</html>
So, for what I needed this is what works.
Based on all of the above solutions this allows me to go from a form to another form, and to the n^ form , all the while preventing the same exact data from being "saved" over and over when a page is refreshed (and the post data from before lingers onto the new page).
Thanks to those who posted their solution which quickly led me to my own.
<?php
//Check if there was a post
if ($_POST) {
//Assuming there was a post, was it identical as the last time?
if (isset($_SESSION['pastData']) AND $_SESSION['pastData'] != $_POST) {
//No, Save
} else {
//Yes, Don't save
}
} else {
//Save
}
//Set the session to the most current post.
$_session['pastData'] = $_POST;
?>
We work on web apps where we design number of php forms. It is heck to write another page to get the data and submit it for each and every form. To avoid re-submission, in every table we created a 'random_check' field which is marked as 'Unique'.
On page loading generate a random value and store it in a text field (which is obviously hidden).
On SUBMIT save this random text value in 'random_check' field in your table. In case of re-submission query will through error because it can't insert the duplicate value.
After that you can display the error like
if ( !$result ) {
die( '<script>alertify.alert("Error while saving data OR you are resubmitting the form.");</script>' );
}
No need to redirect...
replace die(); with
isset(! $_POST['name']);
, setting the isset to isset not equal to $_POST['name'], so when you refresh it, it would not add anymore to your database, unless you click the submit button again.
<?
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
echo "Operation Done";
isset(! $_POST['name']);
}
?>
<form action='page.php' method='post' name="myForm">
<input type="text" maxlength="50" name="name" class="input400" />
<input type="submit" name="Submit" />
</form>
This happen because of simply on refresh it will submit your request again.
So the idea to solve this issue by cure its root of cause.
I mean we can set up one session variable inside the form and check it when update.
if($_SESSION["csrf_token"] == $_POST['csrf_token'] )
{
// submit data
}
//inside from
$_SESSION["csrf_token"] = md5(rand(0,10000000)).time();
<input type="hidden" name="csrf_token" value="
htmlspecialchars($_SESSION["csrf_token"]);">
I think following is the better way to avoid resubmit or refresh the page.
$sample = $_POST['submit'];
if ($sample == "true")
{
//do it your code here
$sample = "false";
}
I am trying to get a form to submit automatically, which feeds a username and password to another form.
If I remove the javascript and just have the form display on the screen, and manually click the Submit button, the result is I get automatically logged in on the resulting page. This is the result I want.
If I leave the javascript in place, it actually doesn't automatically log me in but it does pass across the username and password pre-filled on the resulting page, then I have to click Submit on the resulting page.
How can I make it automatically submit the form to work the same way as a user actually hitting the submit button? Also I understand that this may not be the most secure way to pass a username and password across, but this is for a special use case.
Note: MyForm is a php page, and I am submitting to an aspx page.
Here is code of what my form would look like:
<form id='myForm' method='post' action='https://blah.com/Login.aspx'>";
<p>Username: <input value='usernameHere' name='Username' type='text' id='Username' data-index='0' maxlength='255' placeholder='Username' class='loginUsername' />";
<p>Password: <input value='passwordHere' name='Password' type='password' id='Password' placeholder='Password' />";
<p><input type='submit' name='btnSignIn' value='Sign In' id='btnSignIn' />
</form>
<script type="text/javascript">
document.getElementById('myForm').submit();
</script>
Thank you.
I suspect there are other issues at play, as using JS to submit the form should replicate a native browser submit.
You can try simulating clicking the 'submit' button via JavaScript:
JavaScript:
document.getElementById('btnSignIn').click();
jQuery:
$('#btnSignIn').click();
You can use onload method for javascript
function submitForm() {
// **NOTE** set form values first
document.getElementById('myForm').submit();
}
window.onload = submitForm;
Or with jQuery if you want:
$(function(){
submitForm();
});
or with tag attribute
he typical options is using the onload event:
<body onload="javascript:submitForm()">
.
.
As the problem is supposed "post a form through php" . It may be achived by using PHP€™s functions fsockopen() and fputs() to send properly formatted data to a remote server. Here is a sample of code :
<?php
//create array of data to be posted
$post_data['Username'] = 'XYZ';
$post_data['Password'] = '********';
$post_data['btnSignIn']="Sign In";
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
//we also need to add a question mark at the beginning of the string
$post_string = '?' . $post_string;
//we are going to need the length of the data string
$data_length = strlen($post_string);
//let's open the connection
$connection = fsockopen('https://blah.com', 80);
//sending the data
fputs($connection, "POST /Login.aspx HTTP/1.1\r\n");
fputs($connection, "Host: https://blah.com \r\n");
fputs($connection,
"Content-Type: application/x-www-form-urlencoded\r\n");
fputs($connection, "Content-Length: $data_length\r\n");
fputs($connection, "Connection: close\r\n\r\n");
fputs($connection, $post_string);
//closing the connection
fclose($connection);
?>
The above codes do post your form now to get redirect to that page , use simply
header('location :https://blah.com/Login.aspx ');
I am trying to send an email when an html button is clicked then redirect to an html confirmation page. All my code is in the same php file except for the confirmation page. It redirects with no problem just doesn't send email on button click. It was working at one point but it would send the email as soon as the page loaded. I've searched the internet for days and here is what I'm currently trying:
<form action="confirm.html" method="post" name= "confirm">
<?php
echo('<input type="button" value="Submit" onclick="this.form.submit();">');
?>
</form>
<?php
$to="mail#hello.com";
$subject= "New Application";
$message= "Name: ".$Name;
$headers= "";
mail($to, $subject, $message, $headers);
echo "<body onload=\"self.close();\">";
?>
I am trying to send an email when an html button is clicked then redirect to an html confirmation page.
The above code will send an email as soon as the page loads. If you want to send an email when the form has been submitted, you will need to wrap your emailing code in a post-checking block, the send a location header for the redirect.
You also need some named element with a value to include in the post, for example:
<input type="button" name="submit" value="Submit" />
Then in your PHP you can use
<?php
if (isset($_POST['submit'])) {
// Your email() code
// Redirect to another page
header("Location: http://example.com/confirmation.php");
die();
} else {
// echo/include your form here
}
Be sure to put this code at the top of your PHP page before any HTML has been written or else header() will not function correctly.
I a have PHP form where I collect a bunch of values from text inputs, but for one input I have the input filled in via javascript (user selects a date from a calendar, that date then populates a text input). I've setup a simplified version of this:
<?php
$displayForm = true;
if ($_POST['submitFlag'] == 1) {
// Form was submitted. Check for errors and submit.
$displayForm = false;
$installationTime = $_POST['installation-time'];
// send e-mail notification
$recipients = "test#test.com";
$subject = "Test Email - Test Form Submission";
$message = wordwrap('Someone has filled out the secure form on test.com. Here\'s what they had to say:
Installation Time: ' . $installationTime .'
');
$headers = "From: test#test.com";
mail($recipients, $subject, $message, $headers);
// Output thank you message
?>
<h2>Thank You!</h2>
<?php if($installationTime == NULL){echo 'test failed: value submitted was null.';}else{echo 'test passed: value submitted was not null.';} ?>
<p>Your form has been submitted. Thank you for your interest in test.com.</p>
<?php
}
if ($displayForm) {
// If form was not submitted or errors detected, display form.
?>
<div class="note"><span class="required">*</span> Click me to set value of input.</div>
<form name="contactForm" id="contactForm" method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>?state=submit">
<label for="installation-time" class="service-time">The time you have selected for installation is: <span class="required">*</span></label>
<input type="text" name="installation-time" id="installation-time" disabled value="<?php echo $_POST['installation-time']; ?>" />
<input type="hidden" name="submitFlag" id="submitFlag" value="1" />
<input type="submit" name="submit" id="submit" value="Sign-Up" />
</form>
<?php
} // End of block displaying form if needed.
?>
And then in jQuery I do one of these:
$('.note').click(function(){
$('#installation-time').val('test string');
});
When I submit the form, the PHP variable that's supposed to collect that value is null. Every other input in the form works, and if I remove the javascript and manually enter the exact same text that I had set with JavaScript into the input it works as well.
The question really is why populating a field with javascript as opposed to manually typing the exact same string into a text input would break things. Again there are no errors and the input is populated correctly on the front end. Somehow posting the form just doesn't pick up on the value when it's set by javascript vs. typed manually. There has to be something really fundamental I'm missing here.
Any idea what's going on here? I've spent hours puzzling over this to no avail.
Update:
Code updated, test page:
http://dev.rocdesign.info/test/
Solution: can't post a disabled input. I actually tested that back in the beginning and must have missed that removing the "disabled" on the input made it work, so I mistakenly ruled it out and moved on.
Thanks for the responses everyone. And for anyone else with this problem: use a hidden input to post the value.