How to check for white spaces and special characters - php

I am trying to code a form for a login using php to check it. But I can't get it to check the if I have any whitespaces and special characters for the username. I tried using the [\W]+ but that did not work.
<?php
$usernerr = "";
$passwerr = "";
$usern = "";
$passw = "";
$pattern = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(empty($_POST['uname']))
{
$usernerr = "*Please add a username please!";
}
else
{
$usern = clearInput($_POST['uname']);
if(!preg_match('/s/', $usern) || !preg_match($pattern, $usern))
{
$usernerr = "*Username have only letters and numbers!";
}
$usernerr = "";
}
if(empty($_POST['psw']))
{
$passwerr = "*Please add a password please!";
}
else
{
$passw = clearInput($_POST['psw']);
$passwerr = "";
}
}
function clearInput($input)
{
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
?>

Considering the error message you wrote, you are complicating yourself.
Instead of searching for the list of characters that aren't alpha num, search for alpha num only. Try using this pattern, and don't negate the condition.
$pattern = "/^[a-zA-Z0-9]+$/";
// Some code...
if(preg_match($pattern, $usern))
// ^-------------------------------Notice the changes
{
//Username is valid
}
Description of the pattern :
^ from the begining
[a-zA-Z0-9] search an alpha num
+ 1 or more time
$ to the end
/^[a-zA-Z0-9]+$/can be replaced by /^[[:alnum:]]+$/ or /^[a-z\d]+$/i which produce the same effect.

Related

Password Validation - Legacy Code

The following code validates a new user password by asking them to confirm their password by entering it twice:
// search to see if is a vvalid file path
if (($val["type"] == "password") && !strstr($key , "_confirm")) {
$name = $val["name"] ? $val["name"] : $key ;
if ($input[$name] != $input[$name . "_confirm"]) {
//preparing the message
$fields["error"] = "Password and confirmation doesn't match.";
$fields["errors"][$name] = 1;
$fields["errors"][$name . "_confirm"] = 1;
$fields["values"] = $input;
}
}
I would like to include additional validation (i.e., password contains at least 1 number and 1 letter, special characters [!##$%], must be at least 8 characters in length.
What would be the proper code syntax to nest with the above code? THX
To add the validation, you need to find the Regex you like, e.g.
http://regexlib.com/Search.aspx?k=password&AspxAutoDetectCookieSupport=1
Then use that regex in your code (replace $regEx with your choice):
if (($val["type"] == "password") && !strstr($key , "_confirm")) {
$name = $val["name"] ? $val["name"] : $key ;
if ($input[$name] != $input[$name . "_confirm"]) {
//preparing the message
$fields["error"] = "Password and confirmation doesn't match.";
$fields["errors"][$name] = 1;
$fields["errors"][$name . "_confirm"] = 1;
$fields["values"] = $input;
}
if( !preg_match( $regEx, $input[$name] ) ) {
$fields["error"] = "Password must contain...";
$fields["errors"][$name] = 1;
$fields["values"] = $input;
}
}
For one-upper, one-lower, and one-digit w/ min 8 chars:
$regEx = '/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/';
Add in some special-char requirements:
$regEx = '/^(?=.*[!##$%])(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/';

comparing code in Associative Arrays to hard coded values

I have a text file with the following values which would be used as a username and password
root=>user
roots=>password
blabla=>moonbeam
help=>me
Code for a function validateUser in a file validateUser.php
function validateUser($username, $password)
{
$filename = 'userCreds.txt';
$file = fopen($filename, "r");
if($file==false)
{
echo"Error opening file";
exit();
}
$i=0;
static $Credentials = array();
foreach (file($filename) as $line)
{
list($key,$value) = explode("=>",$line,2) + array(NULL,NULL);
if($value !== NULL)
{
$Credentials[$key] = $value;
}
}
print_r($Credentials);
echo "<br>";
//static $Credentials = array("root"=>"user","rtam"=>"password","q"=>"continuum");
if(array_key_exists($username, $Credentials))
{
echo "$Credentials[$username] <br>";
echo "$password <br>";
if($Credentials[$username] == $password)
{
return TRUE;
}
else
{
echo $Credentials[$username]," is not equal to ",$password,"<br>";
return FALSE;
}
}
else return FALSE;
}
Code for the main file:
<?php
include_once "validateUser.php";
$username = "root";
$password = "user";
if(validateUser($username,$password))
{
echo "<h2>Welcome! <br></h2>";
}
else
{
echo "Try again <br>";
}
?>
The values for $username and password are hardcoded from the beginning for testing purposes.
The problem I have, is when I get to comparing the username and password from the text file and comparing the two, they don't match.
Even when I print out the two values i.e. $password and $Credentials[$username], I get equal values on screen but the if statement doesn't recognize it using if($Credentials[$username] == $password).
What am I doing wrong?
please try to trim the values in your validateuser function - wouldn't be the first time a \n or \t or simple space caught me out.
if($value !== NULL)
{
$Credentials[trim($key)] = trim($value);
}
If that's not the case then maybe you can use regex to strip our any non alphanumeric chars from username and password.
eg
$key = preg_replace('/[^(\x20-\x7F)]*/','', $key);
$value = preg_replace('/[^(\x20-\x7F)]*/','', $value);

php: validate if field starts with certain character

I'm using the Contact Form 7 plugin on wordpress to collect data inputted in the fields, I'm now looking to set up some validation rules using this neat extension: http://code-tricks.com/contact-form-7-custom-validation-in-wordpress/
What I'm after is to only allow one word only in the text field (i.e. no whitespace) and this one word has to begin with the letter 'r' (not case sensitive).
I've written the no white space rule as follows:
//whitespace
if($name == 'WhiteSpace') {
$WhiteSpace = $_POST['WhiteSpace'];
if($WhiteSpace != '') {
if (!preg_match('/\s/',$WhiteSpace)){
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
Is it possible to incorporate the second rule into this also? So no whitespace, and the word must begin with the letter 'r'? Any suggestions would be greatly appreciated!
EDIT:
seems core1024 answer does work, but only one of them:
//FirstField
if($name == 'FirstField') {
$FirstField = $_POST['FirstField'];
if($FirstField != '') {
if (!preg_match("/(^[^a]|\s)/i",$FirstField)){
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
//__________________________________________________________________________________________________
//SecondField
if($name == 'SecondField') {
$SecondField = $_POST['SecondField'];
if($SecondField != '') {
if (!preg_match("/(^[^r]|\s)/i", $SecondField)) {
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
I want to use this code twice, once to validate the first character being a on one field the second instance with the first character being r on another field. But it only seems the SecondField validation rule is working.
Try to use:
preg_match('/^r[^\s]*$/i',$WhiteSpace)
instead of:
!preg_match('/\s/',$WhiteSpace)
You need this:
if (!preg_match("/(^[^r]|\s)/i", $WhiteSpace)) {
It matches any string that doesn't start with r/R or contain space.
Here's a test:
$test = array(
'sad',
'rad',
'ra d'
);
foreach($test as $str) {
echo '"'.$str.'" -> '.preg_match('/(^[^r]|\s)/i', $str).'<br>';
}
And the result:
"sad" -> 1
"rad" -> 0
"ra d" -> 1

PHP Form Validation white space issue

I am trying to validate a form. I have my code as follows:
if(isset($_POST['data'])) {
$id = $this->input->post('id');
$action = $this->input->post('action');
$table = $this->input->post('table');
$data = $this->input->post('data');
$out = array();
$out['id'] = $id;
$out['error'] = '';
$out['fieldErrors'] = '';
$out['data'] = array();
$out['row'] = $data;
if($action=="create" && $data['display_name'] === '') {
if (empty($data['display_name']))
{
$this->_out['error'] = "Display name is required";
echo json_encode( $this->_out );
exit;
}
}
}
Now this is working fine if there is no data inserted in the form, but if there is a space (whitespace) it doesn't work.
Any suggestion?
There are a few options to solve this:
Replace all whitespaces with nothing:
if (strlen(preg_replace('/\s/', '', $data['display_name'])) == 0)
{
Use trim to remove leading and trailing whitespaces:
if (strlen(trim($data['display_name'])) == 0)
{
Use str_replace() to get rid of invalid characters:
if (strlen(str_replace(array(' ', "\t"), array('', ''), $data['display_name'])) == 0)
{
Use regular expression to validate a name:
if (!preg_match('/^([A-Za-z0-9-_]+)$/', $data['display_name']))
{
=== checks for type as well along with value comparison, using trim function on variable containing values would give you expected results.
Try this. I have used the ctype_space function below to check for whitespaces
if($action=="create" && ($data['display_name'] === '' || ctype_space($data['display_name']))) {
$this->_out['error'] = "Display name is required";
echo json_encode( $this->_out );
exit;
}
Just use trim function and check if its empty string:
if ($action=="create") {
if (trim($data['display_name']) == '') {
$this->_out['error'] = "Display name is required";
echo json_encode( $this->_out );
exit;
}
}

highlighting word containing invalid character in php

How to highlight word containing not allwowed character in php
Below is code to find error in a sting $noticeText
function AddressOnlyValidatorNoticeTemp($str_fieldValue)
{
$str_pattern = '/[^A-Za-z0-9 #.,:()%?!^[#\]*{}\/&_-\\s]/'; // 25-08-2010
preg_match_all($str_pattern, $str_fieldValue,$matches);
if($matches[0] != null)
{
$message = "Only 'A-Z a-z 0-9 # . , ( ) & % ? [ ] # * { } _ / -' Characters Allowed";
}
else
{
$message = 1;
}
return $message;
}
if (!$errFlag)
{
$errMsg = AddressOnlyValidatorNoticeTemp($noticeText);
if ($errMsg != 1)
{
$errMsg = "Notice Details : ".$errMsg;
$errFlag = true;
}
}
My issue is how to highlight word containing character not allowed in $str_pattern.
Thanks

Categories