I have a php form that is adding information to my sql database, i need it to only accept numbers in the text box.
This is my php form
<form id="MakeBid" action="MakeBid.php" method="POST">
<input type="hidden" name="propertyID" value="1" />
<div>Bid Now
<input type="text" name="pricesoldfor" />
</div>
<input id="submit" input type="submit" value="Submit" />
</form>
Client-side for feedback without loading, you can do something like
<form [...] onsubmit="if( !this.pricesoldfor.match(/\d+/) ) {
alert('Please enter only numbers for the price!'); return false;
}">
(I've written this example inline - as your form will probably be larger, I would advise you not to use the attribute onsubmit and instead attach a proper event handler. Have a look at preventDefault() as well as this is usually a better alternative to return false.)
What you will really need to do is validate in your PHP (server-side) that it is only numbers before you save it to the database. For example like this:
if((string)(int)$input === $input) { /*was a number*/ } else { /*was not a number*/ }
Bear in mind both of these will only allow full numbers (integers), so no "35.43" or similar. Have a look at is_numeric()
You can use javascript for client-side validation. This isnt very secure, but its fast and can be used to provide a responsive user experience, but should always be backed up with server-side validation.
You can use a mix of regular expressions and if/else or case/switch to see what characters have been typed in.
if (!preg_match("/^[0-9]", $textfield))
// display error message
$num = 123456;
if(!filter_var($num, FILTER_VALIDATE_INT))
{
echo("Not number");
}
else
{
echo("Number");
}
visit for all type of validation
http://www.position-relative.net/creation/formValidator/
and demo is below
http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
Related
I have two forms that are being submitted depending on the conditions.
I used
if(empty($_POST) === false)
to save data after an edit. But for the first time I encountered this situation which causes and error.
What do I need to do so that I can accommodate two forms on a page.???
put a hidden field in each of your forms...
<input type="hidden" name="do" value="edit" />
in the other form:
<input type="hidden" name="do" value="new" />
Then check $_POSTfor those specific values:
if (isset($_POST['do'])) {
// a form was posted
if ($_POST['do']=='edit') {
// do sth with form 'edit'
elseif ($_POST['do']=='new') {
// do sth with form 'new'
} // if $_P
} // if isset
I suggest you to use the RESTful approach to this problem. You can check whatever the request method is POST (new) or PUT (edit) and deal with that.
For example if you have two forms, one for edit and one for creating items, you set the method to one of them with:
<form method="PUT" ...>
<form method="POST"...>
and retrieve the method via:
$_SERVER['REQUESTED_METHOD'];
therefore dividing them.
First of all, I don't want to use any framework but I am looking for a good way to use whitelist validation. I am going to apply it on all the user input I receive, I need validation for XSS protection and I also want to apply different formats for example:
Example 1 XSS.
<input type="text" name="test" value="<script>alert('test');</script" />
Example 2 Date.
<input type="text" name="test" value="31-05-2012" />
Example 3 Time.
<input type="text" name="test" value="15:00" />
Example 4 Max length.
<input type="text" name="test" value="short description" />
Example 5 Min length.
<input type="text" name="test" value="min description" />
Example 6 Alphabetic and default symbols only
<input type="text" name="test" value="hello world. This is à ö text input :P :) :S :$ =D !! ??" />
Example 7 Numeric only
<input type="text" name="test" value="1234567890" />
My idea is to build a clientside and server site validation, if the user gets passed through the clientside validation (jQuery) they will get marked as hacker, since it is impossible for default users to pass through the clientside validation.
My question is: What would be the best way to apply client+serverside validation to prevent XSS and apply regular expressions on fields. Are there any lightweight PHP libraries for validation?
I have looked at:
ctype_alpha
preg_match
But I am not quit sure what would be the best one to use, and ctype_alpha is not allowing default symbols etc.
Any advises? Examples? Thanks for your time and reading, and sorry for the hectic question.
It seems you just need some basic validation, not "whitelist" one.
the idea is quite simple.
Create a server-side validation. with ctype_alpha, preg_match and such. (I hope that your question is not about teaching you these functions from scratch).
Create cleint-side validation if you want, by making AJAX calls to the very same validation routines you've used for the (1).
Of course, you have to use both anyway.
Marking users as a hackers seems not the best idea. What you gonna do with marked users?
I've had a similar problem and ended up writing my own "Input-Datatype" classes. This might be a bit excessive if you only use them for validating input though. But you could build validation functions that use a mix of PHP functions such as preg_match, is_numeric, strtotime etc...
An example for date validation would be:
public function validate(&$value) {
$date = strtotime($value);
if($date === false){
//Error no valid date
}else{
if(isset($this->maxDate)){
if($date>strtotime($this->maxDate)){ //maxDate being the maximal date allowed
//Error max date exceeded
}
}
if(isset($this->minDate)){
if($date<strtotime($this->minDate)){ //minDate being the minimal date allowed
//Error date too low
}
}
$value = strftime($this->format,$date); //format being the format in which the date should be saved
}
Another example for validating text could be:
public function validate(&$value) {
if (isset($value) && $value != "") {
if(isset($this->maxLength)&&$this->maxLength!= ""){ //maxLength being the maximal number of characters
if (strlen($value) > $this->maxLength) {
//Error max length exceeded
}
}
} else {
if (!$this->allowNull) { //allowNull being a boolean: true if text can be empty
//Error value is empty
}
}
if(isset($this->regex)&&$this->regex!= ""){ //regex can be any regular expression, e.g: /[A-Za-z]/ for letters only
if(!preg_match($this->regex, $value)){
//Error value does not match expression
}
}
}
As far as XSS goes, make sure you use prepared statements when interacting with a database and use htmlentities when displaying user inputted data.
Hope this helps.
Some time ago, i've written a lightweight-validation class. Maybe you can use it.
For example:
$oValidator = new Validator();
$oValidator->setLanguage('en');
$oValidator->isValid('short description', 'max_length[4]');
echo $oValidator->getLastErrorMessage();
//The input can not exceed 4 characters in length.
$oValidator->isValid('min description', 'min_length[5]');
$oValidator->isValid('hello world. This is à ö text input :P :) :S :$ =D !! ??', 'min_length[5]');
$oValidator->isValid('1234567890', 'digits');
Rule definition:
/**
* #ErrorMessage[lang=de] Die Eingabe muss mindestens %d Zeichen lang sein.
* #ErrorMessage[lang=en] The input must be at least %d characters in length.
*/
public function check_min_length($mValue, $aParams)
{
return (strlen($mValue) >= $aParams[0]);
}
Example:
http://sklueh.de/2013/01/lightweight-php-validator-neue-version/
github:
https://github.com/sklueh/Lightweight-PHP-Validator
I have a basic form, which i need to put some validation into, I have a span area and I want on pressing of the submit button, for a predefined message to show in that box if a field is empty.
Something like
if ($mytextfield = null) {
//My custom error text to appear in the spcificed #logggingerror field
}
I know i can do this with jquery (document.getElementbyId('#errorlogging').innerHTML = "Text Here"), but how can I do this with PHP?
Bit of a new thing for me with php, any help greatly appreciated :)
Thanks
You could do it it a couple of ways. You can create a $error variable. Make it so that the $error is always created (even if everything checks out OK) but it needs to be empty if there is no error, or else the value must be the error.
Do it like this:
<?php
if(isset($_POST['submit'])){
if(empty($_POST['somevar'])){
$error = "Somevar was empty!";
}
}
?>
<h2>FORM</h2>
<form method="post">
<input type="text" name="somevar" />
<?php
if(isset($error) && !empty($error)){
?>
<span class="error"><?= $error; ?></span>
<?php
}
?>
</form>
If you want change it dynamically in client-side, there is no way but ajax. PHP works at server-side and you have to use post/get requests.
Form fields sent to php in a $_REQUEST, $_GET or $_POST variables...
For validate the field param you may write like this:
if(strlen($_REQUEST['username']) < 6){
echo 'false';
}
else{
echo 'true';
}
You can't do anything client-side with PHP. You need Javascript for that. If you really need PHP (for instance to do a check to the database or something), you can use Javascript to do an Ajax call, and put the return value inside a div on the page.
I've just discovered the email-address-saving form on my website does not work on Opera and Internet Explorer (7 at any rate), and possibly other browsers. Works fine with Firefox. Unfortunately I'm not a developer and no longer have any contact with the guy who wrote the code for the form so I've no idea how to fix it. I assume the problem has something to do with the code below:
<?php
$str = '';
if (isset($_POST['submit']))
{
if(!eregi("^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$", $_POST['email'])) {
$str = "<span style='color: red'>Not a valid email address</span>";
} else {
$file = 'emails.txt';
$text = "$_POST[email]\n";
if (is_writable($file)) {
if (!$fh = fopen($file, 'a')) {
exit;
}
if (fwrite($fh, $text) === FALSE) {
exit;
}
fclose($fh);
}
header('Location: thankyou.html');
}
}
?>
and then the body bit:
<form action="index.php" method="post">
<input type="text" name="email" style="width: 250px;" />
<input type="image" src="img/button-submit.png" name="submit" value="Submit" style="position: relative; top: 5px; left: 10px" />
</form>
<?php echo $str ?>
Anybody feeling pity for a helpless non-dev and have an idea what's not working here?
This is being caused by the fact that the submit input is of type 'image'. On submit, IE7 only returns the x and y coords of the click.
This should do the trick:
Replace:
if (isset($_POST['submit']))
With:
if (isset($_POST['submit']) || isset($_POST['submit_x']))
It is a browser based issue
in your form, you have used <input type="image" />
IE doesn't pass name/value pairs for image type input, instead it only sends the key_x/value_x and key_y/value_y pairs
you probaly want to use <input type="submit" /> as replacement/addition, since this is completely supported on all types of browsers (think also about text browsers please, i still use them.)
Unfortunately, the error, if any at all, is going to be between the Browser and the server, not PHP. If you could provide some details like the HTML form that isn't working in IE7, then we may be able to help out more.
Your form element is self-closed. Remove the trailing / in the opening tag and it should work. (Er, it might work. Either way, there shouldn't be a trailing slash.)
Assuming that the php in your code is in the same file as the form ... you might try adding the name of your php file to the form's action.
<form action="" method="post">
... becomes ...
<form action="name_of_php_file" method="post">
Include a hidden field in your form that will only be valid and present if you submit the form. Something like:
<input type="hidden" name="checkemail" value="1" />
Then, in your PHP, change the if-condition to check for this particular variable:
<?php
$str = '';
if (isset($_POST["checkemail"]))
{
//-- rest of your code
}
?>
This will allow you to keep the image as the submit button and work across browsers which differ in how they send the value, if at all, of the name of image type buttons.
I know this doesn't fix your problem, but I don't like the line:
$text = "$_POST[email]\n";
Is that not bad practice? I haven't used PHP for years, but I think you should change it to
$text = $_POST['email'] . "\n";
or something like that. Using $_POST[email] without the quotes around the array key causes PHP to first look for a constant named 'email'. Only after not finding it will it convert email to a string and then pull the value out of the associative array. Just wasted CPU power.
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.