I have a minor problem. When I use this code:
<!DOCTYPE HTML>
<html>
<head>
<title>Declare Nerf War!</title>
</head>
<body>
<?php
$form="<center><form action='decwargen.php' method='POST'>
Your Name: <input type='text' name='yname' placeholder='John Doe'><br>
Opponent's Name: <input type='text' name='oname' placeholder='Jane Doe'><br>
Why? <input type='text' name='why' placeholder='for stealing my stuff'><br>
Date of war: <input type='text' name='dwar' placeholder='10/11/13'><br>
Time of war: <input type='text' name='twar' placeholder='10:56 PM'><br>
Created on: <input type='text name='crtd' placeholder='10/10/13'><br>
<input type='submit' name='subbut' value='Submit'></center>
</form>";
$ok = $_POST ['subbut'];
if($ok){
$yname = $_POST ['yname'];
$oname = $_POST ['oname'];
$why = $_POST ['why'];
$dwar = $_POST ['dwar'];
$twar = $_POST ['twar'];
$created = $_POST ['crtd'];
echo("<center><h1>Declaration of war</h1><br><p contenteditable='true'>I, " . $yname . " declare war on " . $oname . " for/because " . $why . ". This will happen on " . $dwar . " at " . $twar . ".<br>Created on" . $created);
} else echo($form);
?>
</body>
</html>
The web browser says:
Notice: Undefined index: subbut in /Applications/MAMP/htdocs/decwargen.php on line 17
when I first go to the page, then
Notice: Undefined index: crtd in /Applications/MAMP/htdocs/decwargen.php on line 24
when I enter data. Can anyone please help?
Change your
<input type='text name='crtd' placeholder='10/10/13'>
-------^ quote not closed properly
to
<input type='text' name='crtd' placeholder='10/10/13'>
From your recent question edit, also make the following change:
Replace your
$ok = $_POST ['subbut'];
if($ok){
to
if(isset($_POST ['subbut']))
{
As an additional safety tip, DO NOT EVER print something without sanitizing it.
-- edit --
When writing any code that can accept user submitted content, you need to bear in mind that user content can never be trusted. Malicious users can submit specially crafted data that could allow them to gain access to your application, the end user's computer, or much more.
One way to reduce (or control) the threat is to do the following:
Validate the data: Make sure that the type of data matches what you expect for a field (number, text, email, etc).
Sanitize the data: Perform some cleanup to remove undesirable things contained in the data.
Validate the legitimacy of the form (Optional but recommended): If applicable, ensure that the code is being submitted by a form that was truly generated by your web site and use CAPTCHA to prevent automated content submission when possible.
Escape the data: When displaying the data or passing it on to other systems (database, api call, etc.), make sure that you escape the received data so that it does not negatively after those systems.
You can get more information about doing these things and much more using a simple Google search. You can also look at PHP Sanitize filters
Now going back to the actual code that was used in the original question.
I have taken the liberty to print the form below the declaration of war so that you can declare even more wars if you wish.
The code looks like the following ...
<!DOCTYPE HTML>
<html>
<head>
<title>Declare Nerf War!</title>
</head>
<body>
<?php
$form="<center><form action='decwargen.php' method='POST'>
Your Name: <input type='text' name='yname' placeholder='John Doe'><br>
Opponent's Name: <input type='text' name='oname' placeholder='Jane Doe'><br>
Why? <input type='text' name='why' placeholder='for stealing my stuff'><br>
Date of war: <input type='text' name='dwar' placeholder='10/11/13'><br>
Time of war: <input type='text' name='twar' placeholder='10:56 PM'><br>
Created on: <input type='text' name='crtd' placeholder='10/10/13'><br>
<input type='submit' name='subbut' value='Submit'></center>
</form>";
$ok = $_POST['subbut'] ?? false;
if($ok){
$yname = $_POST['yname'];
$oname = $_POST['oname'];
$why = $_POST['why'];
$dwar = $_POST['dwar'];
$twar = $_POST['twar'];
$created = $_POST['crtd'];
echo "<center><h1>Declaration of war</h1><br><p contenteditable='true'>I, " . $yname . " declare war on " . $oname . " for/because " . $why . ". This will happen on " . $dwar . " at " . $twar . ".<br>Created on " . $created;
};
?>
<hr>
<?php echo $form; ?>
</body>
</html>
I realize that the question was originally asked in 2013. Still, I am going to solve the Notice: Undefined index: subbut ... using a more modern PHP feature.
I would replace ...
<?php
$ok = $_POST ['subbut'];
with ...
<?php
$ok = $_POST['subbut'] ?? false;
You can find out more about the new PHP Null coalescing operator (the Elvis operator ??) at http://php.net/manual/en/language.operators.comparison.php#example-105
When you submit and declaration of war, you will have something similar to the following image ...
HTML Injection
Now, you are going to see what happens with your form when someone performs a simple HTML injection on your page.
Instead of submitting the name as John Doe, I am going to submit John Doe</form><form action="http://example.com" target="_blank"><input value="You got hacked">
The result is visible on the following image ...
If you try to submit another declaration, you will notice that the form will be submitted to the example.com domain. That's because:
The </form> tag will try to close the current form in case the submitted value was printed inside a form. If there was no form to close off, than the tag will be invalid and the browser will ignore it.
Then, my new form is added using <form action="http://example.com" target="_blank">. Browsers will usually reject a nested form tag. Because of this, my form will take over the next form by invalidating its opening tag.
Someone could argue by saying that the original example was not printing a form. Sure. But that does not change what I am trying to convey.
Instead of creating a form, I could have injected a tag what would load an elaborate Javascript application that would then run on your site's domain and do whatever is possible using Javascript. I could have also added an iframe or other things.
The bottom line is, do not use or directly print anything submitted to your script. Heck, you cannot even trust content coming for your own database because you don't know if it's been altered by someone else. You still need do perform some clean up to guard against XSS and CSRF using the data.
When you first go to the page
$_POST['subbut']
Does not exist. It only exists once the form has been posted. In order to avoid this you need to use isset. For example use the following code instead
if(isset($_POST ['subbut'])){
$yname = $_POST ['yname'];
$oname = $_POST ['oname'];
$why = $_POST ['why'];
$dwar = $_POST ['dwar'];
$twar = $_POST ['twar'];
$created = $_POST ['crtd'];
echo("<center><h1>Declaration of war</h1><br><p contenteditable='true'>I, " . $yname . " declare war on " . $oname . " for/because " . $why . ". This will happen on " . $dwar . " at " . $twar . ".<br>Created on" . $created);
} else echo($form);
Also change this line
Created on: <input type='text name='crtd' placeholder='10/10/13'><br>
to this
Created on: <input type='text' name='crtd' placeholder='10/10/13'><br>
You have a quote mistake. Try to change
type='text name='crtd'
to
type='text' name='crtd'
Related
Hello i try to send an array multiple times from html form and later access this value's but im recieving undefined index. Can you please explain me what am i doing wrong here ?
First i take all values of checked checkboxe's
<label>
<input type="checkbox" class="ck" name="event[]" id="event" value="<?php echo $row['name'];?>"><span>Wybierz</span>
</label>
Later on i process it and return values into hidden input fields
$event = $_POST['event'];
foreach ($event as $key) {
echo "<input type='text' class='form-control' name='event2[]' value='" . $key . "' />";
}
And lastly i want to send this data together with some other input fields data to thankyou.php but im getting undefined index on my event2
if (isset($_POST['submit2'])) {
if(count($_POST['name']) > 0) {
$event2 = $_POST['event2'];
print_r($event2);
}
exit;
}
Till step 3 everything works perfectly fine .
On each request, only the values that are in the current form are sent to the server. If you want to keep them through multiple requests, either you save them in the session or output them as hidden fields in your form.
change this line:
$event = $_POST['event'];
to this line:
$event = $_POST['event[]'];
Let me know if that worked! :)
Status:
Apprentice.
My PHP knowledge:
Beginner level.
What I am trying to achieve with my PHP code:
Update the health bar input when ever the user clicks on the submit button.
<form>
<input type="submit" value="Attack">
</form>
So if the condition is true and the post has been done then I want to subtract 25 from the variable health which is then equal to another variable named input.
The problem:
I cant figure out why the health is not updating and how to save the updated value even if the user refreshes and then substracting 25 with the updated health everytime the user clicks on "attack".
What I tried:
Apart from doing some PHP research about Session_start() im not sure how to use it in this context. Im not even entirely sure why my conditional is faulty. I get no error messages what so ever but when I remove my if statement and echo the my bar variable then it doesnt work either as I dont get any number at all, which of course makes me suspect that my math is not working.
<?php
$health = 100;
$input = "";
$bar = '<div>' . $health . $input . '%' . '</div>' . '<div>' . 'Stamina' . '</div>';
echo $bar;
if (isset($_POST['submit'])) {
$health - 25 == $input;
echo $bar;
}
?>
Question:
Why does'nt my value of health / input update? How can I save the session and substract from the new variable the next time an attack is made?
Your PHP is stateless so it has no record of what health was - it's simply reset to 100 every time.
You need to either use sessions, or simply pass back in the value of health each time:
<?php
$health = (isset($_REQUEST['health']) ? (int) $_REQUEST['health'] : 100);
if (isset($_REQUEST['submit'])) {
$health = $health - 25;
}
$input = "";
$bar = '<div>' . $health . $input . '%' . '</div>' . '<div>' . 'Stamina' . '</div>';
echo $bar;
?>
<form action="attack.php" method="post">
<input type="submit" name="submit" value="Attack">
<input type="hidden" name="health" value="<?php echo $health; ?>">
</form>
A couple of other points:
1) I'm not sure what the significance of $input is
2) You should really include a method in your form tag of either get or post - in the PHP I've used I have referenced $_REQUEST which features the values of both $_GET and $_POST
3) Notice I cast the value of $_REQUEST['health'] to an integer because this is output in the hidden HTML field and this helps to avoid XSS exploits.
If you want the health variable to carry over on to other pages or scripts then you might prefer to use a session. Revised code as follows:
<?php
session_start();
$health = (isset($_SESSION['health']) ? $_SESSION['health'] : 100);
if (isset($_REQUEST['submit'])) {
$health = $health - 25;
$_SESSION['health'] = $health;
}
$input = "";
$bar = '<div>' . $health . $input . '%' . '</div>' . '<div>' . 'Stamina' . '</div>';
echo $bar;
?>
<form action="attack.php" method="post">
<input type="submit" name="submit" value="Attack">
</form>
One final comment is that using the session method a user cannot tamper with their own health score. Whereas using the hidden input method the user could potentially change the value of the field and tamper with their health score if they had the technical know-how.
change the form to the form below -
<form action='' method='POST'>
<input type="submit" name='submit1' value="Attack">
</form>
Then you can do -
if (isset($_POST['submit1']))
{
echo "button was pressed";
/// do other stuff.....
}
Define your form like:
<form method="POST">
That might do the trick. And you might need an hidden input field for the current health.
Firstly, forms default to a GET method if omitted.
Therefore, you need to specify it in your form tag
method="post"
Then your conditional statement will fail, since the submit input doesn't have the name attribute.
Add name="submit" to it.
Then this $health - 25 == $input; that doesn't make any sense and I don't know what you're trying to do here.
As stated in another answer by Mr Carrot, you'd want to use $health = $health - 25;
I'll let you look through the answers given, but this gives you a good indication as to what's going on.
Using error reporting would have signaled notices.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
I've have this bit in my processor.php file...
session_start();
$_SESSION['address'] = $_POST['field_2'];
$_SESSION['name'] = $_POST['field_1'];
Those variables are being passed to another page and pre-filling inputs on a second form like this...
<input type="hidden" name="Name" value="<?php echo $_SESSION['name']?>">
<input name="Address" type="text" value="<?php echo $_SESSION['address']?>">
Then that form is being submitted to email...
mail($to, $subject,"Form data:
Name: " . $_POST['Name'] . "
Property Address: " . $_POST['Address'] . "
More Fields ", $headers
);
The email comes through successfully with the pre-filled "Property Address" but "Name" is blank. Why is the hidden input not passing the variable for $_POST['Name']?
While it seemed like the hidden field was the problem, it was not. Every thing was working except for the second line here.
mail($to, $subject,"Form data:
Name: " . $_POST['Name'] . "
Email: " . $_POST['Email'] . "
Property Address: " . $_POST['Address'] . "
Lots More Fields ", $headers);
The whole `mail()' function bit was a copy-and-paste snip-it from the web into Sublime Text. The syntax was perfect, but I eventually found that there was an invisible non-ASCII character in the Name line left over from the copy paste from web snip-it operation. I checked if anyone else ever had a similar problem like this and immediately found this FileUtils.mv throwing Invalid char \302 and \255 exception
The moral of the story is that saving time by using snipits may not always save you time. I should have enabled "draw_white_space" in Sublime Text and I would have probably caught it a lot sooner.
As Fred -ii- pointed out the message body arguments all would have been better concatenated as a $message variable. Whose advice I've now followed.
At step 2, check in the generated HTML code if the "value" attribute have the correct value.
Also, instead of using at step 3 $_POST['Name'] , use $_REQUEST['Name']. With this, it will work if POST or GET request.
I'm trying to accept a form and write it to a CSV (invisible to the people submitting the form, but I can look at it as a compilation of everyone's entries on the server when I feel like it). Every time someone enters the form, it will become a new line on the CSV. To show that the people are actually submitting, a new tab will pop up with a little "thank you" like message and their submission so they can make sure it's theirs. Yes, I do have a JS form validation that works perfectly, but since that doesn't have a problem I left it out to save space.
Here is my current problem. In Firefox, I just get a blank new tab and nothing changes on my--blank--CSV, which is titled testForm.csv. In Chrome, a new tab opens that contains all the code on my php document, and my CSV stays blank.
Here's the snippet of my HTML:
<html>
<body>
<form name="Involved" method="post" action="postest.php" target="_blank" onsubmit="return validateForm();">
Name: <br><input type="text" name="name" title="Your full name" style="color:#000" placeholder="Enter full name"/>
<br><br>
Email: <br><input type="text" name="email" title="Your email address" style="color:#000" placeholder="Enter email address"/>
<br><br>
How you can help: <br><textarea cols="18" rows="3" name="help" title="Service you want to provide" style="color:#000" placeholder="Please let us know of any ways you may be of assistance"></textarea>
<br><br>
<input type="submit" value="Submit" id=submitbox"/>
</form>
</body>
<html>
Here is postest.php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$help = $_POST['help'];
$csvData = $name . "," . $email . "," . $help . '\n';
echo "Thank you for your submission! We'll get back to you as soon as we can!";
echo "I'm " . $name . ", my email is " . $email . ", and I can help in that: \n" . $help;
$filepointer = fopen('testForm.csv','a');
if ($filepointer){
fwrite($filepointer,$csvData);
fclose($filepointer);
exit();
}
?>
I checked out this question about echoing to see if that was my problem. I asked this question before and nobody seemed to find anything wrong with my code other than the obvious $_POSTEST problem. This page looked like what I was going for, but wasn't. This question kind of had what I was going for but didn't actually have the POST code and the answer was one of the most useless things I've ever read (in a nutshell: "Just do it. It isn't that complicated." and some links to other SO questions, which I followed). They brought me here and here. I put exit(); after fclose() like it seemed to work for the first one (it did nothing). With the second, the user's code was too far removed from the codes I've been looking at for me to change my code over to what he/she was doing. I've been searching a lot, and doing extensive googling, but I'm going to cut my list of research here because nobody wants to read everything; this is just to prove I tried.
Let me know if there's anything else you need; I am a complete php novice and it's probably something very basic that I missed. On the other hand, I'm not seeing any major differences between my code and others' at this point.
Try something like this :
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$help = $_POST['help'];
$filepointer = fopen('testForm.csv','a');
fputcsv($filepointer, array($name,$email, $help));
echo "Thank you for your submission! We'll get back to you as soon as we can!";
echo "I'm " . $name . ", my email is " . $email . ", and I can help in that: \n" . $help;
?>
This is the error :-
---> $filepointer = fopen('testForm.csv','a');
$fp = fopen('testForm.csv','a');
if ($fp){
fwrite($fp,$csvData);
fclose($fp);
exit();
}
And the real issue is developing without
display_errors = On
log_errors = On
Look for these parameters in the php.ini file, and turn them on, unless you are developing on a live server, in which case, you really should set up a test environment.
and then not looking at the php error log
UPDATE
There was only one line to change actually, here is the complete code.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$help = $_POST['help'];
$csvData = $name . "," . $email . "," . $help . '\n';
echo 'Thank you for your submission! We\'ll get back to you as soon as we can!';
echo '\"I\'m \"' . $name . ", my email is " . $email . ", and I can help in that: \n" . $help;
$fp = fopen('testForm.csv','a'); // only line changed
if ($fp){
fwrite($fp,$csvData);
fclose($fp);
exit();
}
?>
Your error is really basic and I am ashamed of you. Your problem is obviously that you have not been using a server, nor do you have a PHP package installed on your computer. When you told your computer target="_blank" and method="post", it knew what you wanted, being HTML. However, not having anything that parsed PHP, it had no idea how to read your code and came up as a blank page in Firefox and a block of code in Chrome.
You, indeed, have no idea what you are doing.
how can I post back the data that are already in the text field?
example:
if I miss one of the required field an error will prompt when i click the submit button.
How can I make an post back data in that form using php or javascript and make the cursor of the mouse directly located to the field that caused an error?
There is no automated ways in PHP to write back the informations of the fields so you just have to echo it back.
Let's say you've got a "username" field ( <input type="text" name="username" /> ) you just need to add this:
value="<?php echo isset($_POST['username']) ? $_POST['username'] : ''; ?>"
or if you like more:
value="<?php if(isset($_POST['username'])) echo $_POST['username']; ?>"
changed "" to ''
This sounds like basic form validation. I would recommend reading some of these tutorials or looking for some pre-built PHP form validation mechanisms.
Form validation using PHP
PHP/CSS Form validation
PHP Form Validation
Some frameworks such as CodeIgniter will do this for you if you use their own libraries. It's worth checking out such a framework as they provide a lot of other benefits. Of course it's not always possible to transfer an existing application but it's still useful to bear in mind for the future.
If I understand this correctly you want to keep whatever data the user has already entered, tell him what he did wrong and preferably focus on the bad field.
If so then here's a very basic example using a form with two fields where both need to be filled in to proceed.
<?php
$field1=$_POST['field1'];
$field2=$_POST['field2'];
$badField="";
if($_POST['form_action']=="submitted") {
//Check incoming data
if(empty($field1)) {
$badField="field1";
echo 'field1 is empty<br>';
}
elseif(empty($field2)) {
$badField="field2";
echo 'field2 is empty<br>';
}
else { //Everything ok - move to next page
header('Location: <next page>');
}
}
echo '<form name="mybo" action="' . $_SERVER['PHP_SELF'] . '" method="POST">
<input type="text" name="field1" value="' . $field1 . '"><br>
<input type="text" name="field2" value="' . $field2 . '"><br>
<input type="submit" name="Submit" value=" Enter ">
<input type="hidden" name="form_action" value="submitted">
</form>';
//Focus on empty field
if(!empty($badField)) {
echo '<SCRIPT language="JavaScript">
document.mybo.' . $badField . '.focus(); </SCRIPT>';
}
?>
I think the Moav's answer is "philosophically" correct however if you want do that you can:
1) pass via GET or POST the text control id;
2) on the server check that error condition;
3) fill an hidden input field with that value on the page returns
4) if error that with JS you can do:
window.onload = init; // init stuff here
function init()
{
checkForError();
}
function checkForError()
{
var h = document.getElementById("error_field");
var v = h.value;
if(v)
document.getElementById(v).focus();
}
However, if you will do that for every error field there will be a post and this is
by a user perspective very boring...so it is better to adopt other approaches...
I would take a different approach:
Validation should be in JS, and as such you never loose data, as you don't submit.
Any wrong data that was submitted and caught on the server is due to someone trying to pass over your JS validation, which means he has criminal thoughts, usually.