Removing arbitrary characters in php - php

Please see the following code. I want to remove all the unauthorized characters such as . / \ | !##$%^&*() _ - = + ~ < > , ? : ; " ' [] { } and the ` character and and all the empty spaces input.
I want receive only English characters and Numbers allowed.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = test_input($_POST["user"]);
$password = test_input($_POST["pass"]);}
How should be the test_input() function?

function test_input($string){
if(preg_match('/[^a-z_\-0-9]/i', $string))
{
echo "not valid string";
}
}

Related

How to check for white spaces and special characters

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.

Disabling some characters with preg_match

I'm having an issue with my register page, i noticed that people can register with alt codes like this "ªµµª" and i tried to fix it by using preg_replace but when i did that i couldn't register anymore, atleast not with the worldwide alphabet
final public function validName($username)
{
if(strlen($username) <= 25 && ctype_alnum($username))
{
return true;
}
return false;
}
Tried to fix it by replacing it with this
if(strlen($username) <= 25 && preg_match("/[^a-zA-Z0-9]+/", $username))
But i'm obviously doing something wrong...
Apparently, you are confusing two different uses of the caret (^) metacharacter.
Indeed, it may be two things in a regular expression:
It may assert the start of the subject, which is what you probably want.
It may negate the class, which is what you're doing in your code.
Source: http://php.net/manual/en/regexp.reference.meta.php
Here is a modified version of your code, with the caret (^) and dollar ($) signs to assert the start and the end of the strings you're analyzing:
function validName($username)
{
if (strlen($username) <= 25 && preg_match("/^[a-zA-Z0-9]+$/", $username))
{
return true;
}
return false;
}
$names = array(
'Abc1',
'Abc$',
"ªµµª"
);
foreach ($names as $name) {
echo "<br>" . $name . ': ' . (validName($name) ? 'valid' : 'invalid');
}
// -- Returns:
// Abc1: valid
// Abc$: invalid
// ªµµª: invalid
Note that you may reduce the code inside your function to one line:
function validName($username)
{
return strlen($username) <= 25 && preg_match("/^[a-zA-Z0-9]+$/", $username);
}

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,}$/';

How to escape only certain characters

php function preg_quote escapes these characters . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
Could you please suggest what I could use to escape these characters: + - && || ! ( ) { } [ ] ^ " ~ * ? : /
Edited (as requested by "on hold"):
I'm implementing a Solr search and it says:
Solr gives the following characters special meaning when they appear
in a query:
+ - && || ! ( ) { } [ ] ^ " ~ * ? : /
To make Solr interpret any of these characters literally, rather as a special character, precede the
character with a backslash character .
This may help you:
<?php
$subject = "+ - && || ! ( ) { } [ ] ^ \" ~ * ? : /";
$result = preg_replace('%([+\-&|!(){}[\]^"~*?:/]+)%', '\\\\$1', $subject);
echo $result;
?>
http://ideone.com/EYV1ID
Maybe not the best approach but will work:
str_replace('+','\+',$MyString);
str_replace('-','\-',$MyString);
...............................;
...............................;
Working function
function escapeWildcards($s){
$escapeChars = [ '%', '_'];
foreach ($escapeChars as $escapeChar){
$s = str_replace($escapeChar, '\\'.$escapeChar, $s);
}
return $s;
}

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