Am stuck on how to get the check mark to pop up every time it meets a requirement. So if all the requirements are met I only get a check mark for having a number but no others. Also are there any other way I can improve my code. All my invalids pop up so all I have left is to just get the check marks to work.
<?php
$username =(isset($_POST['username']) ? $_POST['username'] : "");
$password = (isset($_POST['password'])? $_POST['password'] : "");
$login= False;
$Formula='/(?=.*\d)/';// Digits
$Formula2='/(?=.*[!##$%\^&\?])/';//Special Characters
$Formula3='/(?=.[a-z])/';// Lower case letter
$Formula4='/(?=.*[A-Z])/';// Upper case letter
$Formula5='/(?=.{8,16})/'; // Length at least 8-16 characters
$Formula6='/(\S)/';// No white spaces
$Vaild= "<div>✅</div>";
$Invalid ="<div>🚫</div>";
if(isset($_POST['Submit'])){
if(preg_match($Formula,$password)){
echo"$Vaild.You have a number.";
}else{
echo"$Invalid Invalid password must have at least one number.<br/>";
if(preg_match($Formula2,$password)){
echo "$Vaild You have a special character";
}else{
echo"$Invalid Invalid password you need to have at least one special characters.<br/>";
if(preg_match($Formula3,$password)){
Echo"$Vaild You met the lower case letter requirement.";
}else{
echo "$Invalid Invalid password you need to have a lower case letter .";
if(preg_match($Formula4,$password)){
echo" $Vaild You have met the upper case letter requirement.";
}else{
echo "$Invalid Invalid password you need to have a upper case letter .";
if(preg_match($Formula5,$password)){
echo"$Vaild You have met the requirement of having eight to sixteen characters.";
}else{
echo "$Invalid Invalid password you need to be eight to sixteen characters long.";
if(preg_match($Formula6,$password)){
echo"$Vaild You have met the requirement of no white spaces.";
}else{
echo "$Invalid Invalid password you can't have any white spaces in your password.";
}
}
}
}
}
}
}
if(!$login){
?>
<form name ="loginForm" action="part2.php" method="POST">
Username :<input type="text" name="username"
value="<?php echo $username;?>"/><br/>
Password: <input type ="password" name="password"
value=""/><br/>
<input type="submit" name="Submit"/>
<?php } ?>
</form>
Suppose I have a form and in the form, there is an input field for the users to put their full names. I want only characters (A-Za-z) and spaces to be submitted by the users.
<form action='page2.php'>
<input type='text' name='fullname'>
<input type='submit' name='submit' value='Submit'>
</form>
I know, it can be done by html. But I want to check in page2 if user has typed anything without (A-Za-z) and spaces. How this check can be performed with php?
Try this
if (!preg_match("/^[a-zA-Z]$/", $user)) {
/// not match
}
if you want to use regex then below is the code to check alphabet only
preg_match('/^[a-zA-Z]+$/', $string);
Regex is big for this kind of tasks.
You can use this :
if (ctype_alpha(str_replace(' ', '', $name)) === false) {
$errors[] = 'Name must contain letters and spaces only';
}
I'm trying to stop users from being able to put any characters in the username box apart from a-z(A-Z), 0-9 and spaces. Here's the HTML to start off with:
<form action='register.php' method='post'>
<div class="field-wrap">
<label>
Username<span class="req">*</span>
</label>
<input type="text" name="username" required autocomplete="nope" />
</div>
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" name="email" required autocomplete="nope" />
</div>
<div class="field-wrap">
<label>
Set A Password<span class="req">*</span>
</label>
<input type="password" name="password" required autocomplete="nope" />
</div>
<button type="submit" class="button button-block" />
REGISTER</button>
</form>
Pretty self explanatory, right?
Here's the PHP on register.php:
$username = $_POST['username'];
$password = $_POST['password'];
if(preg_match('/[^a-zA-Z0-9[:space:]]+$/', $username)){
//pass
}
else{
$message = "Your username may only contain letters, numbers and spaces";
$_SESSION['error'] = $message;
header("Location:auth.php");
}
// do all the other stuff like add user to database etc
header("Location:index.php");
When I try to create a user with a username such as "test##!?*^'/"()", the preg_match function doesn't work. Instead of redirecting back to the login/register page (auth.php), it adds the user to the database and redirects me to the homepage (index.php).
I have also tried /^[a-z0-9 .-]+$/i for the parameters in preg_match but that doesn't work either.
Just a side note, I'm not using this for security reasons, I use stripslashes and mysql_real_escape_string AFTER the preg_match.
Any ideas, or a better way to only allow a-z(A-Z), 0-9 and spaces? I have been trying to solve this for hours now and to no avail. Thanks!
Use this preg_match code to only allow Letters (including uppercase), Numbers, and Spaces:
$Passed = 0;
$username = $_POST['username'];
$password = $_POST['password'];
if(!preg_match("/[^a-z0-9 ]/i", $username)){
$Passed = 1;
//stop header location here.
}
else{
$message = "Your username may only contain letters, numbers and spaces";
$_SESSION['error'] = $message;
header("Location:auth.php");
}
if ($Passed == 0){
header("Location:index.php");
}
About your original question:
This regular expression doesn't work properly due to caret (^) position:
/[^a-zA-Z0-9[:space:]]+$/
↑
In this position, caret negate following pattern inside square brackets. In fact, your pattern search for any not a-zA-Z0-9....
To match a string with only alphanumeric characters and spaces you have to move the caret at start of pattern. In this position the caret means “start of string”:
/^[a-zA-Z0-9[:space:]]+$/
↑
But you can also simplify your pattern, and replace [:space:] with a real blank space ([:space:] and \s match also newline, tab, etc...1). Try this regular expression:
/^[A-z0-9 ]+$/
Your script still not working:
The solution is die().
If the string doesn't match the pattern, you execute this code:
$message = "Your username may only contain letters, numbers and spaces";
$_SESSION['error'] = $message;
header("Location:auth.php");
Sending headers doesn't interrupt the script, so the remaining code is executed and the last sent header (Location:index.php) is loaded.
Force script termination after sending header:
header("Location:auth.php");
die();
1 From PHP documentation: “The "whitespace" characters are HT (9), LF (10), FF (12), CR (13), and space (32). However, if locale-specific matching is happening, characters with code points in the range 128-255 may also be considered as whitespace characters, for instance, NBSP (A0).”
Change your regex to:
/^[\d\w\s]+?$/
You can easy test with http://regexr.com/
Solved this now thanks to Ghulam... his logic was great although the code he wrote was wrong so I've updated it.
Also updated my answer with fusion3k's die(); approach just to make sure the code is completely finished.
$username = $_POST['username'];
$password = $_POST['password'];
$passed = 0;
if(preg_match("/^[A-Za-z0-9 ]+?$/", $username)){
//pass
$passed = 1;
}
if($passed == 0){
$message = "Your username may only contain letters, numbers and spaces";
$_SESSION['error'] = $message;
header("Location:auth.php");
die();
}
if($passed == 1){
//add user to database
header("Location:index.php");
}
We set $passed as 0 to begin with.
If $username only contains letters a-z(A-Z), 0-9 and spaces then we set $passed to 1 as it has passed the preg_match check.
If $username contains any other characters apart from these, (#, %, ^ etc) then we leave the $passed variable as 0.
If $passed is 0 then the username is invalid, so return the user to the register/login page (auth.php) and give them an error message.
If $passed is 1 then the username is valid so we can add the user to the database and return them to the homepage.
die(); is used to make sure the code stops reading/running after the header redirect has been sent. The page might redirect but the user could still be added to the database!
This is a good example for a short security tutorial.
The original code presented by OP allows access if $username does not contains characters from list, at least one of them:
if(preg_match('/[^a-zA-Z0-9[:space:]]+$/', $username)){
//pass
}
The updated code posted here is doing the job:
if(preg_match("/^[A-Za-z0-9 ]+?$/", $username)){
//pass
$passed = 1;
}
However, correctly is to refuse access if $username contains ANY characters outside from the allowed set:
if(!preg_match("/[^A-Za-z0-9 ]/", $username)){
//allows access
$passed = 1;
} else {
//refuse access
$passed = 0;
}
This will cover and refuse anything outside from the allowed character set.
The caret sign "^", usually is a metacharacter that assert start of subject (or line, in multiline mode), like in /^(A sentence).*$/, but when used in a character class, like [^abc] it means "NOT the characters inside the brackets" (reference).
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).
<label for="first_name">* First Name </label>
<input type="text" name="first_name" maxlength="64" value=<?php echo formatPhone(clean_input($_POST['first_name']); ?>>
I have a form where I want to enter a first name. I want the fields to take only alphabets(no numbers). Also when a user enters something like John Doe separated by multiple white spaces, I want it to separate the two words only by a single space. I am not sure how this is done in php.
This will let pass only ascii names and split the input properly:
if (preg_match("~^([A-Z][a-z]+\s*)+$~gm", $value)) {
// valid
$array_of_names = preg_split("~\s+~gm", $value);
// or
$normalized_name = preg_replace("~\s+~", " ", trim($value));
}