Simple php form1 - php

I am trying to write a simple php form but the out put is different from the one I wanted it to be. Does any one see what my mistake is thanks and appreciate it.
The Assignment :
Write a PHP script that checks the message sent from the form and then prints the name of the sender and the message. If the sender name or the message is blank, print ”You didn’t give all required information!” Remove any spaces before or after the user name or message. Remove also any HTML tags to make sure the user can’t alter the guestbook. The used form looks like this:
<form action="guestbook.php" method="get">
Sender: <input TYPE="text" name="name"><br>
Message: <input type="text" name="message"><br>
<input type="submit" value="Send">
</form>
Example output
John: Hello!
**my script:**
<?php
$name = $_GET["name"];
if(isset($_GET['submit'])) {
echo "$name: Hello!";
} else {
echo "You didn’t give all required information!";
}
?>
YOUR PROGRAM DOES NOT OPERATE CORRECTLY
Your program generated the following output:
You didn’t give all required information!
The following output should have been generated:
John: Hello!
The white area indicates correct output from your program.
represents a carriage return
In the comparison of outputs, the output of your program must be exactly the same as the example output.

You have no input named "submit", only one with a type submit, which is what you are looking for. Try using isset($_GET['name']) in the if-statement instead, since that's what you're actually using:
<?php
if(isset($_GET['name']))
{
echo $_GET['name'].": Hello!";
}
else
{
echo "You didn’t give all required information!";
}
?>
You should be aware though that directly outputting user-inputted data like this is very unsafe, creating a very big XSS vulnerability.

if(isset($_GET['submit']))
Should be
if(isset($_GET['name']))

Your PHP should look like the following:
<?php
$name = $_GET['name'];
if($name != ''){
echo "$name: Hello!";
}
else
{
echo "You didn’t give all required information!";
}
?>
Note: I haven't tested this.

In your statement :
if the sender name or the message is blank, print ”You didn’t give all
required information!” Remove any spaces before or after the user name
or message. Remove also any HTML tags to make sure the user can’t
alter the guestbook.
you should have something like this inside of your if statement:
if( isset($_GET['name']) ){
$clean_name = trim(strip_tags($_GET['name']));
echo $clean_name;
}
trim() to remove extra whitespaces before and after of the string and strip_tags() to remove html tag

<form action="guestbook.php" method="get">
Sender: <input type="text" name="name"><br>
Message: <input type="text" name="message"><br>
<input type="submit" value="Send" name="send">
</form>
<?php
if(isset($_GET['send'])) {
$name = trim(strip_tags($_GET['name']));
if($name != ''){
echo "$name: Hello!";
} else {
echo "You didn’t give all required information!";
}
}
?>

Related

Testing PHP POST empty values - unexpected result - What am I missing?

I am following a tutorial but I keep getting a TRUE result that shouldn't be correct if I click the submit button WITHOUT filling in any value in the name field.
The first test works as expected, but the second and third test keep returning TRUE when they should return FALSE (leaving the input empty).
What am I missing, not understanding, or doing wrong? This should be simple.
Any help or suggestions are appreciated.
Here is the very simple script:
<?php
//This one works correctly
if(!empty($_POST['name'])) {
echo "There is input here <br>";
} else {
echo "You have not input any info yet. <br>";
}
//This returns true even if I leave the field empty
if(isset($_POST['name'])) {
echo "A name has been input <br>";
} else {
echo "You have not input your name yet. <br>";
}
//This returns true also when it shouldn't
if(filter_has_var(INPUT_POST, 'name')) {
echo $_POST['name'] . ' <- Name Input!<br>';
} else {
echo 'No Name Input.';
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p><label for="name">Name:</label> <input type="text" name="name"
id="name" size="30" value=""></p>
<p><input type="submit" value="SEND"></p>
</form>
empty does what is says, checks if empty (is empty if not existing aswell)
isset checks if the var exists, no if anything has been set
filter_has_var pretty much the same as isset
place a print_r($_POST) at the top of your file, you will understand :)
You need to check the value to see if it's empty:
if(isset($_POST['name']) && !empty($_POST['name'])) {
http://php.net/manual/en/function.empty.php

Why Won't my PHP Form Code work Correctly?

I am trying to create a form in php with an else/if statement that asks the user for their name and age. It greets them with a welcome message and their name, and then if their age is 16 or over, the statement echos "You are old enough to volunteer for our program." If the user is under the age of 16, the statement will echo "Sorry, try again when you are older. Here is my code:
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_POST['postName'];
?>
!
<br>
<?php
$age = 'age';
if ($age>=16)
{
echo $_POST["you are old enough to volunteer for our program!"];
}
else {
echo $_POST["Sorry, try again when you're 16 or older."];
}
?>
The input form is shown correctly, but "Sorry, try again when you're 16 or older" already appears when I open the web page and when I put my name and age in there, the welcome message with the users name works correctly, but absolutely nothing happens with the age statement. It still just says "try again when you're older" no matter what age I put in. HELP :(
For starters you need to use $_POST["age"] and not age. Also you should check if you are using get or post using $_SERVER['REQUEST_METHOD'].
If ($_SERVER['REQUEST_METHOD'] == "POST") {
// HandleForm
} else {
// showForm
}

How to stop the form input data from erasing after php validation invalid = true?

I have a form which the user enters data eg first name and last name etc. I have PHP validation which checks for empty field. The problem is when the submit button is clicked, the whole form data is erased when a field is left empty.
I tried this method below.
<input type="text" value="<?php echo $_POST["UserName"]; ?>"" name="UserName"
id="UserName" size="20" />
But when the form loads for the first time, inside the text box is this
<br /><b>Notice</b>: Undefined index: UserName in ...... on line <b>477</b><br />
Is there a method to stop the form from being cleared? or to echo the data into the fields?
replace this :
value="<?php echo $_POST["UserName"]; ?>"
in your code with this :
<?php if(isset($_POST["UserName"])) echo $_POST["UserName"]; ?>
The issue here is that you're not checking whether $_POST["UserName"] is initialized, and when it is not, you'll throw the error. Check with isset:
<input type="text" value="<? if isset($_POST["UserName"]) { echo $_POST["UserName"]; } ?>" name="Givenname" id="Givenname" size="20" />
Check if $_POST["UserName"] isset, Try this:
<input type="text" value="<?php echo isset($_POST["UserName"]) ? $_POST["UserName"] : ''; ?>" name="Givenname"
id="Givenname" size="20" />
I think you are using Reset button like this:
<input type="reset" />
Try this:
<input type="submit" />
If you are trying Second one then use required in every input like:
<input required type="text" />
Your form is not being cleared or erased. But you are loading a NEW page with a NEW form.
Your attempt to load the new form is a good one, but you need to change
<input type="text" value="value="<?php echo $_POST["UserName"]; ?>"" name="UserName" id="UserName" size="20" />
into
<input type="text" value="<?php echo isset($_POST["UserName"])?$_POST["UserName"]:""; ?>" name="UserName" id="UserName" size="20" />
So remove the second value=" and the corresponding " which should have never been there. And check if the variable is available before trying to echo it.
In addition to doing this, you might also want to do client side validation in Javascript on top of the server side validation. (Never only do client side validation, by the way, as that can be fooled by end users.)
What you can do is to change your <form> tag into this:
<form action="..." method="post" onsubmit="if (document.getElementById('UserName').value == '') { alert('UserName is still empty'); return false; }">
This will prevent the form from being sent to PHP when UserName is still empty. And thus prevent from the page being reloaded and the form being cleared.
PHP forms will often discard entered data upon error validation, even when echoing it in the input field caches the entry on successful submit, and it is understandable that erasing disallowed data would be the default behavior. However, it can be a real hardship to retype large amounts of text in a textarea, and its sudden vanishing may come as an unwelcome surprise to the user, especially when due to a simple reason such as an over-the-character-number limit.
Setting the $_POST['UserName'] value with the error validation should preserve the field input without allowing its process. The example uses a variable to cache the data and echo it into the input field.
Update: The script has been updated to include multiple submit buttons for the same form, as well as the option for a success message array.
Update: The script has been updated to include an exit() option as well as a textarea.
UserName and First Name allowed characters are defined and will
trigger an error with uppercase A-Z or special characters.
UserName uses the error array, while First Name uses exit() to stop
the script altogether.
Textbox allowances also will trigger an error with uppercase A-Z or
special characters, and use exit() to stop the script.
The form data will be preserved on error message, exit() page return, and successful send.
The form results are printed on successful send.
<?php
/* Define variables and set to empty values.*/
$username=$first_name=$textbox='';
/* If using non-array success variable, initialize it as a string:
$success='';
Otherwise, define as an array. */
/* Submit button is clicked, start validation.
Separate multiple submit buttons (for the same form) with || (|| = OR):
*/
if ((isset($_POST['submit_one'])) || (isset($_POST['submit_two']))) {
// Define error and success messages as arrays to display in a list.
$error=array();
$success=array();
// Validate user input and error characters not lowercase a-z or 1-9.
if (!empty($_POST['UserName'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$username=trim(htmlspecialchars($_POST['UserName'], ENT_QUOTES));
if (preg_match("/^[a-z0-9]+$/", $username)) {
/*
if (preg_match("/^[a-z0-9]+$/", trim($_POST['UserName']))) {
$username=trim(htmlspecialchars($_POST['UserName'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
$error[]='User Name can only contain lowercase a-z and 0-9.';
$username=$username;
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether:
$username=$username;
exit ("Username may only contain lowercase a-z and 0-9. Use the Back-button to try again.");
*/
}
}
else {
$error[]="Please enter a User Name.";
}
if (!empty($_POST['first_name'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$first_name=trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
if (preg_match("/^[a-z0-9]+$/", $first_name)) {
/*
if (preg_match("/^[a-z0-9]+$/", trim($_POST['first_name']))) {
$first_name=trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether. */
$first_name=$first_name;
exit ("First Name may only contain lowercase a-z and 0-9. Use the Back-button to try again.");
/*
$error[]='First Name may only contain lowercase a-z and 0-9.';
$first_name=$first_name;
*/
}
}
else {
$error[]="Please enter a First Name.";
}
if (!empty($_POST['textbox'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$textbox=trim(htmlspecialchars($_POST['textbox'], ENT_QUOTES));
if (preg_match("/^[a-z0-9\ \(\s*\n){2}]+$/", $textbox)) {
/*
if (preg_match("/^[a-z0-9\ \(\s*\n){2}]+$/", trim($_POST['textbox']))) {
$textbox=trim(htmlspecialchars($_POST['textbox'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether. */
$textbox=$textbox;
exit ("Textbox input may only contain spaces, lowercase a-z, and 0-9. Use the Back-button to try again.");
/*
$error[]='Textbox input may only contain spaces, lowercase a-z, and 0-9.';
$textbox=$textbox;
*/
}
}
else {
$error[]="Please enter Textbox content.";
}
// If no errors, process data.
if (empty($error)) {
if (isset($_POST['submit_one'])) {
/* Sanitized submit button per rule #1: never trust user input. Remove sanitization if it causes a system error.
Reiterating ($_POST['submit'] is helpful when using multiple submit buttons.
Wrap each function in the additional submit isset, and end functions with closing (empty($error) else statement. */
$_POST['submit_one']=trim(htmlspecialchars($_POST['submit_one'], ENT_QUOTES));
/* Post data or send email, and print success message.
The array is option. Do not define as an array or use[] to use as a simple variable. */
// Processing data here, for example posting to a database ...
$success[]="The submit_one Send Form request has been processed!";
}
if (isset($_POST['submit_two'])) {
$_POST['submit_two']=trim(htmlspecialchars($_POST['submit_two'], ENT_QUOTES));
// Processing data here, for example sending an email ...
$success[]="The submit_two Process Form request has been sent!";
}
}
/* If errors, show error message.
The exit() option ends the script at the validation check .*/
else {
$error[]="Please correct the errors and try again.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.wrapper {margin: 2% auto; width: 500px;}
textarea {text-align:left;}
</style>
</head>
<body>
<div id="anchor" class="wrapper">
<div>
<form name="data_form" action="#anchor" method="post">
<table>
<tr>
<td colspan="2">
<label for="UserName">User Name</label>
<br>
<input type="text" name="UserName" id="UserName" size="20" value="<?php echo $username; ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<label for="first_name">First Name</label>
<br>
<input type="text" name="first_name" id="first_name" size="20" value="<?php echo $first_name; ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<label for="textbox">Textbox</label>
<textarea name="textbox" id="textbox" style="height:100px; width:98%;text-align:left;"><?php echo $textbox; ?></textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit_one" id="submit_one" value="Send Form">
</td>
<td>
<input type="submit" name="submit_two" id="submit_two" value="Process Form">
</td>
</tr>
</table>
</form>
</div>
<div>
<?php
/* Print errors as a list or print success message.
Separate multiple submit buttons with ||. */
if ((isset($_POST['submit_one'])) || (isset($_POST['submit_two']))) {
if (!empty($error)) {
echo '<h4>The form was not sent due to the following errors:</h4>
<ul>';
foreach ($error as $message) {echo '<li>'. $message . '</li>';
}
echo '</ul>';
}
/* Print success confirmations as a list for processed input. */
else {
echo '<h4>The form has been sent!</h4>
<ul>';
foreach ($success as $message) {echo '<li>'. $message . '</li>';}
/* If using a success variable without defining it as an array,
initialize it as a variable at the top of the script,
then print variable without <ul>s and foreach loop:
echo '<p>' . $success . '</p>';
*/
echo '</ul>
<h4>Processed Data:</h4>
<ul>
<li>User Name: ' . $username . '</li>
<li>First Name: ' . $first_name . '</li>
<li>Textbox: <br>' .
/* Replace $textbox new lines with <br> tags. */
nl2br($textbox) .
'</li>
</ul>';
}
/* Unset foreach loop data. */
unset($message);
}
?>
</div>
</div>
</body>
</html>

contact form in email not returning values

I'm using CKEditor to create a html mailer in which a contact form is being sent to email.
The problem is, there is no value being received on submission of that form in email.
Contact Form in E-Mail (code)
<form action="http://techindiainfotech.com/mail.php" method="post" name="test">
<p>Your Name: <input maxlength="75" name="name" size="75" type="text" /></p>
<p>Mobile Number: <input maxlength="10" name="mobile" size="10" type="text" /></p>
<p>Business Name: <input maxlength="100" name="business" size="100" type="text" /></p>
<p><input name="sub" type="submit" value="Submit" /></p>
</form>
Handler - mail.php
if ($_POST['sub'] != '') {
unset($_POST['sub']);
echo "Details received:<br>";
foreach ($_POST as $val) {
echo "$val<br>";
}
} else {
header("Location: http://www.techindiainfotech.com/files/contact_us.php");
exit();
}
Screenshot from gmail's Message Text Garbled
if ($_POST['sub'] != '') {
unset($_POST['sub']);
The above code means: if $_POST['sub'] is not an empty string, evaluate the statements below.
If your form wasn't submitted, $_POST['sub']; will be undefined and PHP will throw an error saying Undefined index.
I'd use isset() instead to properly check if the form was submitted or not.
if (isset($_POST['sub'])) {
# code ...
}
The following should work:
if (isset($_POST['sub']))
{
unset($_POST['sub']);
echo "Details received:<br>";
foreach ($_POST as $val)
{
echo "$val<br>";
}
}
Your form is so simple and the $_POST loop, that it narrows down the error sources:
file base: scripts are not in the folder you expect
CKEditor throws out HTML, either you strip it or,... have a look into the HTML sourcecode.
Use print_r($_POST); at the beginning of mail.php
enable PHP debugging / error reporting: http://blog.flowl.info/2013/enable-display-php-errors/
if you have javascript we cannot see in your sample code, remove it for further testing
Update:
the CKEditor changes your inputs in a way that they are not anymore labeled by name attributes or renders the form in any other invalid form (don't think that's the problem)
I copied your sample code onto my webserver and it's working. You might have something in your real code that doesn't appear in the code above.
Everything was fine except for the one, the form action attribute.
I'm submitting the form to http://techindiainfotech.com/mail.php but due to .htaccess it is being redirected to http://www.techindiainfotech.com/mail.php and that's why the request has been lost (I'm not getting the appropriate word here).
So, I just need to change in my action attribute which is, submit my form to http://www.techindiainfotech.com/mail.php not to http://techindiainfotech.com/mail.php.

Is there something wrong with my form?

I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?
I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""
I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.
I tried using
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?
Form code:
echo ' <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
Name: <input name="name" type="text" /><br />
Email: <input name="email" type="text" /><br />
Phone Number: <input name="phone" type="text" /><br /><br />
Comment: <br/>
<textarea name="comment" rows="5" cols="30"></textarea><br /><br />
<input type="submit" name="submit" value="Submit Email"/>
</form></div>
<div style="clear:both;"></div><br /><br />';
and the vaildator:
if(isset($_POST['submit'])) {
$errors = array();
if (empty($name)) {
$errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
}
if (empty($phone) || empty($email)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!is_numeric($phone)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
$errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
}
if ($errors) {
echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
} else {
mail( "email#hotmail.com", "Monthly Specials Email",
"Name: $name\n".
"Email: $email\n".
"Phone Number: $phone\n".
"Comment: $comment", "From: $email");
echo'<span id="valid">Message has been sent</span><br/>';
}
}
First: you cannot trust '.$_SERVER it can be modified. Be carefull with that!
Second: you could(should?) use a hidden field instead of specifing it in the action?
But if you have an error, it refreshes
the page and removes any text that was
inserted before the submit button was
clicked and you have to re-enter all
of the information. Anyway to fix
this?
You could use ajax to fix it(I believe plain old HTML has this side-effect?).
A browser doesn't have to (p)refill a form. Some do for convenience, but you cannot rely on it.
In case you display the form again, you could set the values of the inputs like this:
$value = isset($_POST['foo']) : $_POST['foo'] : '';
echo '<input type="text" value="'. $value .'" name="foo" />';
Of course you should check and sanitize the POSTed data before including it in your HTML to not open up any XSS vulnerabilities.
If you want the form to submit to the same page, you don't need to set an action, it works without it as well. Also I'd suggest you to send the date in this way:
<input type="hidden" name="date" value="'.$date.'"/>
A part from the fact that that validator and html code has some big issues inside and things i'd change, what you are asking is: How could i make that the form compiled doesn't remove all the text from my input tags after the refresh.
Basically not knowing anything about your project, where the strings submitted goes, if they are stored in a database or somewhere else, what does that page means inside your project context i cannot write a specific script that makes submitted string remembered in a future reload of the page, but to clarify some things:
If there is a form that is defined as <form></form> and is submitted with a <input type="submit"/> (which should be enough, without giving it a name name="submit") the page is refreshed and it does not automatically remember the input your previously submitted.
To do that you have 2 choice:
Use Ajax (check Jquery as good framework for ajax), which will allow you to submit forms without refreshing the page. I choose it as first way because it is over-used by everyone and it is going to became more and more used because it is new and it works smoothly.
Make a php script that allows you to check if the input has already been submitted; in case the answer is true, then recover the values and get them in this way: <input type="text" value="<?php echo $value ?>"/>.
Also notice that you do not need of '.$_SERVER["PHP_SELF"].'?date='.$date.' since ?date='.$date.' is enough.
Browsers will not re-populate a form for you, especially when doing a POST. Since you're not building the form with fields filled out with value="" chunks, browsers will just render empty fields for you.
A very basic form handling script would look something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] = 'POST') {
# do this only if actually handling a POST
$field1 = $_POST['field1'];
$field2 = $_POSt['field2'];
...etc...
if ($field1 = '...') {
// validate $field1
}
if ($field2 = '...') {
// validate $field2
}
... etc...
if (everything_ok) {
// do whatever you want with the data. insert into database?
redirect('elsewhere.php?status=success')
} else {
// handle error condition(s)
}
} // if the script gets here, then the form has to be displayed
<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($field1) ?>" />
<br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($field2) ?>" />
etc...
<input type="submit" />
</form>
?>
Notice the use of htmlspecialchars() in the last bit, where form fields are being output. Consider the case where someone enters an html meta-character (", <, >) into the field. If for whatever reason the form has to be displayed, these characters will be output into the html and "break" the form. And every browser will "break" differently. Some won't care, some (*cough*IE*cough*) will barf bits all over the floor. By using htmlspecialchars(), those metacharacters will be "escaped" so that they'll be displayed properly and not break the form.
As well, if you're going to be outputting large chunks of HTML, and possibly embedding PHP variables in them, you'd do well to read up on HEREDOCs. They're a special construct that act as a multi-line double-quoted string, but free you from having to do any quote escaping. They make for far more readable code, and you don't have to worry about choosing the right kind of quotes, or the right number of quotes, as you hop in/out of "string mode" to output variables.
first, a few general changes:
change
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
to
<form method="post" action="'.$_SERVER["PHP_SELF"].'">
<input type="hidden" name="data" value="'.$date.'" />
the answer to your original question:
set each input elements value attribute with $_POST['whatever'] if array_key_exists('whatever', $_POST);
For example: the name field
<input type="text" name="name" value="<?php echo array_key_exists('name', $_POST) ? $_POST['name'] : ''; ?>" />

Categories