So I've always heard and read that you need to sanitize any user input if it's to be output back to html. What I'm wondering is, do I need to sanitize any input that is output if there was an error?
For example, in my form error handling, I have it so the page gets re-displayed with the error message showing and telling the user what went wrong but also outputting their input as the form's value so they don't have to re-type it and they can see where they went wrong. My question is do I need to use htmlspecialchars() to sanitize the user's input when its output as the value of the form field?
Here is what one of my input fields looks like right now.
<label for="email">E-mail Address: <?php if($btnPressed) { checkInput($_POST['email'], true, true); } // Check the validity of the input ?></label>
<input type="text" name="email" id="email" value="<?php if($btnPressed) { echo $_POST['email']; } // Output the user's input if an error occurred ?>" maxlength="50" />
Here is what I think I should be doing.
<label for="email">E-mail Address: <?php if($btnPressed) { checkInput($_POST['email'], true, true); } // Check the validity of the input ?></label>
<input type="text" name="email" id="email" value="<?php if($btnPressed) { echo htmlspecialchars($_POST['email']); } // Output the user's input if an error occurred ?>" maxlength="50" />
Any help is greatly appreciated.
Yes, you need to run the data through htmlspecialchars.
Otherwise you have two major problems.
A third party could link (or submit a hidden form with JS (since you are using $_POST they would have to use this approach)) to your site sending whatever data they liked (including "><script...) as the user who visited their attack site.
If the user enters a " in their data (either because it is a typo or because their data really does include a " character), it will break when you display it back to them.
Related
!
I would like to see on my page a simple text which reminds the subscriber has to edit are preson name and in his profile.
This text would show only if the wordpress user profile name is empty.
Someone has an idea of php code?
I have this on my HTML profil page, as input.
When this input is empty I would like to display a little message in php.
input class="input-text" name="account_first_name" id="account_first_name" value="" type="text"
Tank you, am using woocommerce
Maybe placeholder is what you want?
<input class="input-text" name="account_first_name" id="account_first_name" value="" type="text" placeholder="Remember to edit this!">
If not and you want to use PHP to check if a variable is empty then use the empty function.
<?php
$name = "";
if(empty($name)){
echo "Remember to edit name";
}
?>
I have a basic contact form on my website and I am trying to add the PHP ucwords() function of PHP to the form for the users first_name and last_name fields so they capitalize the first letter correctly. How would I add this to the actual HTML form?
Edit: I want these changes to be applied only after the user submits the form. I don't really care about how the user types it in. I just need someone to actually show me an example.
Like how would I add the PHP ucwords() code to this simple form?
<!DOCTYPE html>
<html>
<body>
<form action="www.mysite.com" method="post">
First name: <input type="text" name="first_name" value="" /><br />
Last name: <input type="text" name="last_name" value="" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
I am assuming I do something like value='<php echo ucwords() ?>' but I have no idea how?
Thanks!
When user submit the form you can access the submitted information through $_POST variable [because method="post"] of PHP and in action you have to specify the actual page where you need the submitted information to be process further
<?php
// for example action="signup_process.php" and method="post"
// and input fields submitted are "first_name", "last_name"
// then u can access information like this on page "signup_process.php"
// ucwords() is used to capitalize the first letter
// of each submit input field information
$first_name = ucwords($_POST["first_name"]);
$last_name = ucwords($_POST["last_name"]);
?>
PHP Tutorials
Assuming short tags are enabled:
$firstName = 'Text to go into the form';
<input type="text" name="first_name" value="<?=ucwords($firstName)?>" />
Otherwise as you stated
<input type="text" name="first_name" value="<?php echo ucwords($firstName); ?>" />
Assuming you wanted to do it without a page refresh, you need to use Javascript. Simplest way would be to add an onkeyup event to the input field and simulate PHP's ucwords functions, which would look something like...
function ucwords(str) {
return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
Edit: In response to your edit, if you want to get the value they sent with ucwords applied, all you need to do is $newVal = ucwords($_POST['fieldName']);
How do I show a message from the php action script of a form?
The form is a user login with these fields.
<div id="register_user_box" class="inline_form" style="position: absolute; top: 20px; right: 10px; <br/>
<span id="user_msg"></span><br/>
<form action="register_user.php" method="post">
<input type="hidden" name="id" id="id" value="add" />
<input type="hidden" name="edit_user" id="edit_user" value="y" />
<table cellspacing="0px"> <tr><td>Username:</td></tr><tr><td>
<input type="text" name="uname" size="30" value="" class="inline_input"/></td> </tr> <tr><td>Email:</td></tr><tr><td>
<input type="text" name="uemail" size="30" value="" class="inline_input"/></td> </tr> <tr><td>Password:</td></tr><tr><td>
<input type="password" name="upass" size="30" class="inline_input"/></td> </tr> <tr><td>Confirm Password:</td></tr><tr> <td>
<input type="password" name="cpass" size="30" class="inline_input"/></td></tr> </table></td></tr> </table> <p>
<input class="button" type="submit" name="register" value="Register" style="float:right;"/></p>
</form>
</div>
The php script register_user.php checks the if the passwords match and shows an error message if they don't. The script checks all the other fields and prints a message if necessary.
<?php
$messages = array( 'usr_cred_req' => 'Must specify username, email, password.',
'usr_name_bad' => 'Bad username selection. Select a different usrename.',
'usr_name_exists' => 'Username selected already exists. Select a different username.',
'usr_email_bad' => 'Bad email selection. Select a different email.',
'usr_email_exists' => 'Email selected already exists. Select a different email.',
'usr_pass_notmached' => 'Passwords do not match. Type passwords again.',
'usr_not_added' => 'User not added.',
'usr_not_updated' => 'User not updated.',
'usr_added' => 'User added.'
);
$username = trim($_REQUEST['uname']);
$email = trim($_REQUEST['uemail']);
$password = md5(trim($_REQUEST['upass']));
$copasswd = md5(trim($_REQUEST['cpass']));
if ( $password != $copasswd ) { echo '<script> $("#usr_msg").html("'.$messages['usr_pass_notmached'].'"); </script>'; return;}
?>
The error message isn't shown and the browser leaves the page. I'd like the browser to stay on the page and add the error message to the span user_msg.
If you don't want the browser to leave the page when the form is submitted, then you will have to use AJAX to submit the form in the background to communicate with the server and then update the container with the error message (or something different on success).
Alternatively, have the PHP form post to itself, check the error messages before you output your HTML and if there was an error, insert the error message in the form markup in the desired location and re-populate the form with all of the values that were originally submitted.
http://jquery.malsup.com/form/
Here's a good jQuery AJAX form plugin. This will prevent page refresh upon submission.
Hope this helps.
Why are you echoing a JS script to display the error message? The way you have it written out it won't display a little popup, you just having it filling the span. A better way to do it is something like this:
if ( $password != $copasswd ) {
$display_msg = $messages['usr_pass_notmached']
}
Then in your HTML do this:
<span><?php echo $display_msg?></span>
If the variable is empty then nothing is displayed. If you do this for all the fields, then you can ensure all the information from the form is returned on error, whether the actual field IS the error or not, preventing the user from having to retype all the information again. Have the form do a $_SERVER['PHP_SELF'] to ensure it reloads the same page
I would build the PHP functionality (which can't be turned off by the user) and ensure your form works properly 100% (or close to that) of the time. Then, once you have that script working, add your JS funcionality to compliment your existing code.
What I do in mine, is I build an extra array, in this case $display_msg and I run a check of all the input fields. If a field fails, I add that to the array, $display_msg['password'] then I move on to the next field. Once all the fields have been check, I check if the $display_msg variable is empty or not. If it's not empty, then I have it fill all the span next to the input boxes with red letters explaining the error. This will print out ALL of the errors at the same time, instead of one at a time while it works it's way down the form. Next to each input I have a span with the given variable name, in this instance <?php echo $display_msg['password']?>, then next to the username, <?php echo $display_msg['username']?> and so on. Hope this is clear enough and helps.
I could use some guidance in how to proceed on form validation in CodeIgniter. I am using CodeIgniter's built-in form validation and works fine as far as it goes. It returns individual error messages for each field where there is an error by using and wrapping it in some HTML/CSS for styling:
<?php echo validation_errors('<p class="error">'); ?>
But what we want to do is highlight the fields where there are errors. CI will let you put the error messages next to where the form errors are. But it requires you to use the error message for the value, like this:
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
which by the way is in CI's manual in non-CI syntax, which puzzles me. Anyway, we also want the data from the field when the form is submitted to be preserved and returns. So I've done:
$email = array('name' => 'email', 'value' => $em);
?><div style="padding:5px;">Email* </div><?php echo form_input($email) . '<br/>';
$em is returned from the controller like this:
$data['em'] = $this->input->post('email');
So my question is, how do I accomplish all of what is outlined above? Obviously, what CI suggests and what I have done collide. But I don't know how else to do it, so I could use some help.
EDIT: Upon further digging, I see that you can put the error message next to the field by doing this:
<?php echo form_error('email'); ?>
But I'm not getting any message upon an error, even though I have the rule written and I get an error with the first line of code above.
form error($field) returns an empty string '' so better use:
<input type="text" name="email" <?php if (form_error($email) !=='') { echo 'class="error"'; } ?> value="<?php echo set_value('email'); ?>" size="50" />
Tested.
In order to display error individually you should use the function form_error('email'). And for you to get a value of a field being checked, use the function set_value('email'). For these two functions to work, you would have had to, in your controller, set a rule for the 'email' field. Where you specify wich validation rules apply to that field.
<?php echo form_error('email'); ?>
<input type="text" name="username" value="<?php echo set_value('email'); ?>" size="50" />
source: http://codeigniter.com/user_guide/libraries/form_validation.html#individualerrors
untested, but form_error($field) should return true if there is an error:
So perhaps:
<input type="text" name="email" <?php if (form_error($email)) { echo 'class="error"'; } ?> value="<?php echo set_value('email'); ?>" size="50" />
untested. worth a shot?
Perhaps also consider using JQuery or similiar to validate and style the form fields, and use CI as a fallback (for presentation purposes, obviously).
That way your form validation can be styled as you required without CI limitations for 99% of validation rules, and then anything else, the default CI way can kick in.
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'] : ''; ?>" />