In PHP is this enough to guarantee a form has been submitted by clicking the form submit button and to verify the content posted is not empty?
if($_SERVER['REQUEST_METHOD']=='POST' && !empty($_POST['field_data']))
{
echo "ok";
}
I think, there may be a way to be sure the form was submitted using your form.
If I would like to do it, I think I will make something like this :
$secure = $_SESSION['form']['submit'] = MD5(time());
<form>
<input type='hidden' name='secure_form' value='<?php echo $secure ?>' />
</form>
And else when submitted check the value :
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['secure_form']) && $_SESSION['form']['submit'] == $_POST['secure_form']) {
//do stuff
}
Of course, you have to add session_start() at the top of the page!
first you need to check $_SERVER['REQUEST_METHOD'] output so best way to convert output in upper
if(strtoupper($_SERVER['REQUEST_METHOD']) === 'POST') {
Then you can check with submit button name also like
<input type="hidden" id="submitted" name="submitted" value="yes"/>
if(strtoupper($_SERVER['REQUEST_METHOD'])=='POST' && isset($_POST['submitted']) && $_POST['submitted'] == 'yes'){
also you can check all values of form which will be submitting by isset() or empty()
I tend to use a hidden form field
<?php
$csrf_token = md5(time().'random string');
$_SESSION['csrf'] = $csrf_token;
?>
<input type="hidden" id="submitted" name="submitted" value="yes"/>
<input type="hidden" id="csrf" name="csrf" value="<?php echo $csrf_token; ?>"/>
Then in my PHP I'd use something like:
if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['submitted'] == 'yes' && $_POST['csrf'] == $_SESSION['csrf']){
// Do something
echo 'Form submitted via POST';
}
Updated to include a CSRF field
Related
As stated above, when I try to send a form using php my if statement is not being triggered and the variable is not being set to my desired value.
Relevant PHP:
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST['time_pickedm']) == "9:00"){
$timepicked = "09:00:00";
}
}
Relevant HTML:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<input type="button" class="<?php echo $buttoncolour ?>" name= 'time_pickedm' value = "9:00">
<input type="submit" class="btn btn-primary" name="Submit">
</form>
Any help would be appreciated
Your condition is wrong, try:
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST['time_pickedm']) && $_POST['time_pickedm']== "9:00"){
$timepicked = "09:00:00";
}
}
EDIT:
I think i found it!
in your html you have 2 buttons, so the time_pickedm is not going to your php. try replacing button for text:
<input type="text" class="<?php echo $buttoncolour ?>" name= 'time_pickedm' value = "9:00">
You if condition invalid .If time_pickedm is present in array is always true .
its just like if(true == "9:00")
So Change to separate validate the condition
if(isset($_POST['time_pickedm']) && $_POST['time_pickedm'] == "9:00")
I'm new to PHP and trying to write code to test whether or not a user has clicked a radio button in response to a survey question. There are numerous radio buttons. If they haven't clicked on one then I'd like to issue an error to the user. I've tried a couple of approaches, but haven't found anything that works. Here is my current code and the error message I get. For the PHP script, I've tried all of the three following examples:
....
if ($_POST['degree_type'] == "MS"||"MA"||"MBA"||"JD"||"PhD") {
$degree_type = ($_POST['degree_type']);
} else if ($_POST['degree_type'] == null) {
$errors[] = 'Please select a degree type.';
}
if (isset($_POST['degree_type'])) {
$errors[] = 'Please select a degree type.';
} else {
$degree_type= $_POST['degree_type'];
}
if (array_key_exists('degree_type', $_POST)) {
$degree_type = ($_POST['degree_type']);
} else {
$errors[] = 'Please select a degree type.';
}
....
Here is my html, located in the same page and below the PHP.
<table>
<tr>
<td class="span6">What type of degree?</td>
<td class="span6">
<input type="radio" name="degree_type" value="MA"
<?php if (($_POST['degree_type']) == 'MA') {echo 'checked="checked"';} ?>
>MA
<input type="radio" name="degree_type" value="MS"
<?php if (($_POST['degree_type']) == 'MS') {echo 'checked="checked"';} ?>
>MS
<input type="radio" name="degree_type" value="MBA"
<?php if (($_POST['degree_type']) == 'MBA') {echo 'checked="checked"';} ?>
>MBA
<input type="radio" name="degree_type" value="JD"
<?php if (($_POST['degree_type']) == 'JD') {echo 'checked="checked"';} ?>
>JD
</td>
</tr>
ETC....
I get an "undefined index" error on each of the HTML lines referencing a radio button. I understand this might be easier to do in JavaScript, but I don't know much about JS... A detailed response would be much appreciated!
Thanks!
If you're getting an undefined error on the HTML page, just can add an isset() check to the logic where you're printing out the value. E.g.:
<input type="radio" name="degree_type" value="JD" <?php if (($_POST['degree_type']) == 'JD') {echo 'checked="checked"';} ?> >JD
Becomes
<input type="radio" name="degree_type" value="JD" <?php if (isset($_POST['degree_type']) && $_POST['degree_type'] == 'JD') {echo 'checked="checked"';} ?>>JD
An 'undefined index' error in PHP means that you are using an undefined variable in an expression. So for example, when you did:
<?php if (($_POST['degree_type']) == 'MA') {echo 'checked="checked"';} ?>
$_POST['degree_type'] was undefined. There's a couple of different possible reasons why the variables are undefined. I'd have to see the rest of the PHP file to know the exact cause.
One reason could be that the form was not properly submitted. Another reason could be that the expression was evaluated before the form was submitted.
Either way, the code below should work. Note that I'm checking if each field is set before attempting to validate it or compare it's value.
NOTE:
Obviously you have to have a proper HTML doctype, opening and closing body tags etc. The HTML in this example is only the form portion of the page.
<!-- myform.php -->
<form name="my-form" method="POST" action="/myform.php">
<span>What degree do you have?</span>
<label for="bs">BS</label>
<input type="radio" name="degree" id="bs" value="BS" <?php if(isset($degree) && $degree == 'BS') echo 'checked="checked"';?> />
<label for="ma">MA</label>
<input type="radio" name="degree" id="ma" value="MA" <?php if(isset($degree) && $degree == 'MA') echo 'checked="checked"';?> />
<label for="phd">PHD</label>
<input type="radio" name="degree" id="phd" value="PHD" <?php if(isset($degree) && $degree == 'PHD') echo 'checked="checked"';?> />
<span>Which do you like better?</span>
<label for="steak">steak</label>
<input type="radio" name="food" id="steak" value="steak" <?php if(isset($food) && $food == 'steak') echo 'checked="checked"';?> />
<label for="lobster">lobster</label>
<input type="radio" name="food" id="lobster" value="lobster" <?php if(isset($food) && $food == 'lobster') echo 'checked="checked"';?> />
<input type="hidden" name="submitted" value="submitted" />
<input type="submit" name="submit" value="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
$errors = array();
if (isset($_POST['degree'])) {
$degree = $_POST['degree'];
} else {
$errors[] = 'Please select your degree type.';
}
if (isset($_POST['food'])) {
$food = $_POST['food'];
} else {
$errors[] = 'Please select your food preference.';
}
if (count($errors) > 0) {
foreach($errors as $error) {
echo $error;
}
} else {
echo 'Thank you for your submission.';
}
}
?>
The reason you see these notices is because $_POST['degree_type'] is simply not set. Either by typo, or it just didn't get submitted (because you didn't select any before submitting the form).
Also note,
if ($_POST['degree_type'] == "MS"||"MA"||"MBA"||"JD"||"PhD") {
It doesn't work that way. This will check that $_POST['degree_type'] == "MS" OR: "MS" is truthy (always true) OR "MA" is truthy (always true)... see where I'm heading?
if (in_array($_POST['degree_type'], array("MS", "MA", "MBA", "JS", "PhD")) {
Is a better alternative.
Unrelated:
You should really use <label> elements to markup your labels. Example:
<label><input type="radio" name="degree_type" value="MA"> MA</label>.
This will have MA clickable.
When a form is submitted with no member of a radio button group (defined as the group of radio buttons whose name attributes are the same) selected, the submitted data doesn't include that name at all.
This is why you're getting the "undefined index" error (actually a notice); when you test the value of $_POST['degree_type'], and no radio button named "degree_type" was selected, $_POST['degree_type'] doesn't exist at all.
Fortunately, this simplifies your validation task. By calling array_key_exists('degree_type', $_POST), you can find out whether or not the key is present, and thus whether or not a radio button was selected, without prompting the PHP "undefined index" notice. If the function call returns true, you know that a radio button was selected; otherwise, you know one wasn't, and that's what your validation is trying to determine. Therefore:
if (array_key_exists('degree_type', $_POST)) {
$degree_type = $_POST['degree_type'];
}
else {
array_push($errors, "Please select a degree type.");
};
will cleanly accomplish your task.
//set a default
$degree_type = "";
if (isset($_POST['degree_type'])) {
$degree_type = $_POST['degree_type'];
} else {
$errors[] = 'Please select a degree type.';
}
Then instead of using
if (($_POST['degree_type']) == 'MA')
for your checks, use:
if($degree_type == 'MA')
undefined index means that the key you are using hasn't been initialized. So $_POST['degree_type'] won't appear until after the first time the form is submitted.
echo "<form method=\"post\" action=\"settings.php\" onchange=\"this.form.submit()\">";
echo "Announce New Files: <input type=\"radio\" name=\"announcefiles\" value=\"On\" $checkon1> On";
echo "<input type=\"radio\" name=\"announcefiles\" value=\"Off\" $checkoff1> Off<br>";
echo "</form>";
I am trying to get this form to submit when one of the radio buttons is pressed but I'm not sure how to catch the submission.
for example, normally with a submit button you would use something along the lines of if(isset($_POST['submit'])) but I'm not sure how to do it if the form auto submits.
Add hidden input field like:
<input type="hidden" name="action" value="submit" />
Then in PHP check:
if(isset($_POST["action"]) && $_POST["action"] == "submit") { ... }
You should be checking the request method. If you've set things up cleanly, a POST request at that URL will mean a form submit. As you've noticed, you can have attempted submits where a value just isn't there.
if ($_SERVER['REQUEST_METHOD'] === 'POST')
See $_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST' for more discussion.
Give your form a name and check for isset($_POST['form_name']) or check for the name of the radio isset($_POST['announcefiles'])
Also, you don't need all the quote escaping that you have, you can use single quotes as well as use a multiline string - see example below.
echo "
<form method='post' name='form_name' action='settings.php' onchange='this.form.submit()'>
Announce New Files: <input type='radio' name='announcefiles' value='On' $checkon1> On
<input type='radio' name='announcefiles' value='Off' $checkoff1> Off<br>
</form>";
<?php
// Check if form was submitted
if (isset($_POST['form_name']) {
// Form submitted
}
?>
<?php
// Check if radio was selected
if (isset($_POST['announcefiles']) {
// Form submitted
echo 'You chose' . $_POST['announcefiles'];
}
?>
Try this:
You may have an easier time if you separate the php and html a little more.
<form method="post" action="settings.php" onchange="this.form.submit()">
<fieldset>
<legend>Announce New Files:</legend>
<label for="on"><input type="radio" id="on" name="announcefiles" value="On" <?php echo $checkon1 ?> /> On</label>
<label for="off"><input type="radio" id="off" name="announcefiles" value="Off" <?php echo $checkoff1 ?> /> Off</label>
</fieldset>
</form>
Then in your php logic in settings.php ( or above the form if you are posting back to the same page ) you can check for the value of announcefiles:
<?php
if(isset($_POST['announcefiles'])){
// DO SOMETHING
}
?>
Let me know if this helps. Or if I'm missing the question.
every time i am refreshing the page and i am getting the same value stored in the post array.
i want execution of echo statement only after submit and after refreshing no echo results..
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User name : <b> $name </b>";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
From just a form, you won't be able to check if it was a refresh, or a first submit, regardless of using GET or POST method.
To ensure a single message, you need to:
a. redirect the user to somewhere else after you processed the request.
if(isset($_POST['submit'])) {
// process data
header("Location: new-url");
}
And display the message on the other URL.
b. set a cookie / session variable, which tells you the form was already processed.
if(isset($_POST['submit']) && !isset($_SESSION['form_processed'])) {
$_SESSION['form_processed'] = true;
}
This second approach will kill your form until the user closes the browser, so you should do something more complex - like storing another hidden field in the form, and storing that in the session.
If you submit a form and then refresh the resulting page, the browser will re-post the form (usually prompts first). That is why the POST data is always present.
An option would be to store a session variable and have it sent in the form, then check if it matches in the form processing code - to determine if it is a re-post or not.
Within the form:
<input type="hidden" name="time" value="<?php echo $time; ?>" />
In the PHP:
session_start();
if(isset($_POST['submit']))
{
if(isset($_SESSION['time']) && $_SESSION['time'] == $_POST['time'])
{
echo "User name : <b> $name </b>";
}
}
$time = $_SESSION['time'] = time();
Another option is to redirect after processing the post data:
if(isset($_POST['submit']))
{
...
...
header('Location: ' . basename($_SERVER['PHP_SELF']));
exit();
}
You need to maintain a state as to whether $name has already been displayed or not. The easiest way is probably to maintain that state in a browser cookie.
<?php
$nonce = $_COOKIE['nonce'];
$new_nonce = mt_rand();
setcookie('nonce', $new_nonce);
if(isset($_POST['submit']) && $_POST['nonce'] == $nonce)
{
$name = $_POST['name'];
echo "User name : <b> $name </b>";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="nonce" value="<?php echo $new_nonce ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
Problems
you are polluting the user “session” with stale variable.
this will break if your user opens several windows (or tabs) to the same page. To fix this you would have to change the nonce cookie into an array of nonces, and update it accordingly.
if you want refresh page after submit use
<form method="get"
sure if your form hasn't a lot of data and also need to use $_GET instead of $_POST variable:)
correct way for you, but this logic is not good, need to refactor this script:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User name : <b> $name </b>";
unset($_POST['submit']);
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
Hope someone can help me with my code. i am using rewritten URL's and have this piece of code on a form. When the page first loads mypage.htm, the type_24 checkbox get's checked by default. If they check the type_12 box, i want the type_24 box to uncheck.
My problem is, if i check the type_12 box, the page refreshes and both the type_12 and type_24 boxes are checked.. which is not what i want. I think it's because i'm reloading my rewritten URL in my action because it works fine if i just have php file as the action.
Any ideas how i can fix my code so that it only has the type_12 checked when i check the type_24 box?
<form name="frmrefresh" id="frmrefresh" method="post" action="mypage.htm">
<input type="checkbox" name="type_12" id="type_12" <?php if(isset($_POST['type_12']) && $_POST['type_12']=="12"){?> checked="checked"<?php }?> value="12" onClick="uncheck24(this);" /> <label>12</label>
<input type="checkbox" name="type_24" id="type_24" <?php if(isset($_GET['id']) && $_GET['id']!=''){?>checked="checked"<?php }?><?php if(isset($_POST['month_24']) && $_POST['type_24']=="24"){?> checked="checked"<?php }?> value="24" onClick="uncheck12(this);"/> <label>24 Months</label>
<input type="hidden" name="id" value="<?php echo $_REQUEST['id'];?>" />
</form>
In the header i have the functions:
function uncheck12(obj)
{
if (obj.checked == true)
{
document.getElementById("type_12").checked = false;
document.frmrefresh.submit();
}
}
function uncheck24(obj)
{
if (obj.checked == true)
{
document.getElementById("type_24").checked = false;
document.frmrefresh.submit();
}
}
A number of remarks:
Consider using radio buttons instead of checkboxes
I think you mean isset($_POST['type_24']) instead of isset($_POST['month_24'])
As to your problem, I bet your rewrite rule is something like:
RewriteRule ^mypage.htm$ mypage.php?id=5
This means that when the form gets submitted via POST, PHP will still set the $_GET['id'] variable for you since it's in the query string. And since you check the '24' option whenever $_GET['id'] is set, the second checkbox will always get checked.
To fix this you could consider adding the check $_SERVER['REQUEST_METHOD'] == 'GET':
<form name="frmrefresh" id="frmrefresh" method="post" action="mypage.htm">
<input type="checkbox" name="type_12" id="type_12" <?php if(isset($_POST['type_12']) && $_POST['type_12']=="12"){?> checked="checked"<?php }?> value="12" onClick="uncheck24(this);" /> <label>12</label>
<input type="checkbox" name="type_24" id="type_24" <?php if(isset($_GET['id']) && $_GET['id']!='' && $_SERVER['REQUEST_METHOD']=='GET'){?>checked="checked"<?php }?><?php if(isset($_POST['type_24']) && $_POST['type_24']=="24"){?> checked="checked"<?php }?> value="24" onClick="uncheck12(this);"/> <label>24 Months</label>
<input type="hidden" name="id" value="<?php echo $_REQUEST['id'];?>" />
</form>