php validation concept - php

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

Related

How to count integer values stored in a variable using php?

I am developing a web form which have a field 'marks' where user can put marks... I want to force the user to input only marks less then 4 digits. Here is function for this purpose but it is not working...
Function validate($marks)
If(strlen($marks)<=4 && !filter_var($marks, FILTER_VALIDATE_INT)
)
Return false;
Else
Return true ;
This can be achieved using only HTML5 input options (PHP is unnecessary for this application).
If your input is type="number" you can use min=-9999 max=9999 to limit the number to 4 digits.
If your input is type="text" you can use maxlength=4 to limit to 4 characters.
Here is a list of input types and options that might help: https://www.w3schools.com/tags/tag_input.asp
Use the maxlength attribute of the input tag.
e.g.
<input type='text' maxlength='4' name='marks' />
Depending on how you want to implement this, you can use javascript too, which will allow you to display some dynamic warning info when it is less than 4 digits.
If you want to do it with php you can do it like this if the data type is an integer or a float:
if ($marks <= 9999.99) {
//do something
}
If it is a string representation of numbers, you can do it like this:
if (strlen($marks) <= 4) {
// do something
}

how to make a field can not be filled minus or symbol?

So like normal field input, This filed should be filled only by numbers or letters, can not insert like symbol(~!##$/%^&-+=|*.\,) and minus numbers in PHP/html. Can help me please? i done search in internet not found only found for sql or vb
<input type="text" name="text" value="">
where this field will be POST to another php
$name =trim($_POST['name']);
Use this:
bool ctype_alnum ( string $text )
You could use alnum method of respect/validation:
if(v::alnum()->validate($stringToCheck)){
//valid
}
else {
//not valid
}

Allow only numbers and letters in an input box or textarea

I have s form and I want to make it safe so I want to validate each input value before I save it in my database. For example I have this input field:
<input type="text" name="username" value="" />
and now for example, someone fills it with something other than numbers and letters like
myusername12|\/+*()!#$%^#^&_-+=.,';"
which might be dangerous values. So I want to check first if the field contains only letters and numbers and echo "letters and numbers only" otherwise. How can I do that?
PHP has a handy built in function to perform this test.
http://php.net/manual/en/function.ctype-alnum.php
Check this function returns true before attempting to save the data but make sure you're running DB prep anyway.
How about:
if (preg_match('/^[a-z0-9]+$/', $username) {
echo "Looks good\n";
} else {
echo "Invalid character\n";
}
And, if you want to be unicode compatible:
if (preg_match('/^\p{Xan}+$/', $username) {
echo "Looks good\n";
} else {
echo "Invalid character\n";
}
Where \p{Xan} stands for any alpha-numeric.
Not a complete answer for your problem, but html5 can do this for you:
<input type="text" name="username" pattern="![^a-zA-Z0-9]" title="Only digits and letters" />
If the users blurs the input, it will highlight red (in FF at least). Be aware though, this is clientside. You can use the exaxt same regex in php to validate.
You can also save the regex and use it in both:
$regex = "[a-zA-Z0-9]";
if(isset($_POST['username'])){
echo preg_match('/'.$regex.'/', $_POST['username']) ? 'match' : 'no match';
}
echo '<input name="username" pattern="'.$regex.'" title="Only digits and letters" />';
Small note: I dont know if browsers do complex regexes (or do them differently).

How to add validation to my form?

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

Mobile Phone Validation - Php

Apologies to bother you with a question that may seem quite blunt to some of you but I was wondering if any of you could shed some light on the validation side of things
Ive got a text field and I need validation on a mobile number so i need to validate that it has +44 at the beginning and including the +44 that it is 13 digits long , I found a few different techniques but nothing that defined it step by step only just copy and paste , Id like to learn how to do it so I know for future reference.
Any help would be appreciated
Thanks
Although this can be done simply with PHP string functions, I would urge you take this opportunity to learn regular expressions. Once you are ready you can use PHP PCRE functions to apply that regular expression.
Note: This answer is intentionally generalized in the interest of teaching a man to fish, per the OP request. I encourage posting a separate, more specific question after reviewing these resources.
Easy way:
php code:
if (isset($_POST['send'])) {
$mobile = $_POST['mobilenumber'];
// get the first 3 string
$begin = substr($mobile,0,3);
// get the rest of the posted string and add it to 0 to make it to number
// 'intval($variable)' and '(int) $variable' do the same
$theOthers = 0+substr($mobile,3);
// OR $theOthers = intval(substr($mobile,3));
// OR $theOthers = (int) substr($mobile,3);
$ok = true;
echo strlen($mobile);
// check the first 3 string
// if it's not equal with "+44", the entry is wrong
if ($begin != "+44") {
$ok = false;
} else {
// check the length of the input
// if it's not equal with 13, the entry is wrong
if (strlen($mobile)!=13) {
$ok = false;
}
}
if ($ok) {
// do something
}
}
html code:
<form method="post">
<input type="text" name="mobilenumber" maxlength="13" value="+44">
<input type="submit" name="send" value="Send">
</form>

Categories