i have a username but i want to check if the username doenst contain any numbers or other things that does not belong in a username.
Example:
if ($username !contain "1234567890/.,;'\[]") {
send username to db
} else {
echo 'your username is incorrect';
}
How do i do this?
the username is represents the real name in my code.
Among the 1000 ways you can do this, one is regular expressions:
if (!preg_match("![0-9/.,;'\\\[\]]!", $username)) {
//send username to db
} else {
echo 'your username is incorrect';
}
An alternative is to whitelist permitted characters rather than blacklist invalid ones:
//Allows letters and a single quote (not uncommon in some names)
if (preg_match("!^[A-Za-z']+$!", $username)) {
//send username to db
} else {
echo 'your username is incorrect';
}
Try preg_match
Searches username for a match to the regular expression given in pattern.
Related
The user can enter a password into a POST form and the code will search the wordlist $file for the password. If it finds the password in the wordlist, it will inform the user. This works 90% of the time for generic passwords like Banana123 and Brad101. However, if the user enters a password like BananaK123 the code will return nothing. Is there a way to make the code ignore the letter 'K' in the password BananaK123 so it just searches for Banana123 instead?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
function dictionaryCheck() {
$file = file_get_contents("100k-most-used-passwords-NCSC.txt");
if(isset($_POST['dictionaryCheck'])){
$password = ($_POST['password']);
$password2 = preg_replace("/[^a-zA-Z]/", "", $password);
$pos = stristr($file, $password2);
if ($pos === false) {
echo "The dictionary word '$password2' was not found";
} else {
echo "The dictionary word '$password2' was found ";
echo " and exists at position $pos";
}
}
}
}
dictionaryCheck();
Try looking into similar_text(). You may want to reject strings that match a certain similarity.
https://www.php.net/manual/en/function.similar-text.php
This was just to answer your direct question. However, I would not suggest this way. ZXCVBN is a better solution. The reason I am saying this is that you will not be able to tell your users WHY you are rejecting that password. You may cause a lot of frustration.
I want to check the username to contain only letters. If it doesn't contain any letters, the registration I want to fail. Is it good to use preg_match? Now if I input for username: a1, also filling the password, confirm password and type fields the registration is successful.
form.php
if (isset($_POST['submit'])){
/* if the username is alphabetic */
if (ctype_alpha(str_replace(' ', '', $username)) === false &&!empty($username) ) {
$errors[] = 'Userame must contain letters and spaces only';
}
/* if passwords match */
if((!empty($password) && !empty($repassword)) && ($password != $repassword)){
echo "Passwords do not match.";
}
if (!empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['type'])){
$sql = "INSERT INTO users (username, password, type) VALUES ('$username', '$password', '$type')";
$result = mysql_query($sql);
echo 'Successful Registration.';
}
else{
echo 'Please fill all the fields.';
}
}
If you're looking for just letters in the username, preg_match will work for you.
For example,
if(!preg_match("/^[a-zA-Z]+$/", $username)){
// if the username has non-letter characters
}
However, like the comments are saying, there are much better ways to approach preventing SQL injection attacks. Switching to prepared statements is a great start.
This is a snippet of code from source code, which I made to practice my PHP skills. After submitting the login form, I try to see if the username and password that the user submitted using the login form matches with the one stored on database. If yes then "Your username and password matches what I have!" (obviously this is not going to be the final echo but just to see what echo out of the two will it bring). If I give correct creds (user/pass) or incorrect one, it echoes out "Your username and password DOES NOT matches what I have!" block. I don't see any problem with the code, I ran out of ideas.
Part of the code inside config.php (which I have included) is a setup of the database, with a table of registration and few fields, of which username and password fields does exist hence the names.
user is value of the name tag on login form for Username and pass is value of the name tag on login form for Password.
<?php
include("config.php");
if(isset($_POST['submit'])) {
$stmt = $db->prepare("SELECT * FROM registration WHERE username = :username AND password = :password");
$stmt->execute(array("username" => $_POST['user'], "password" => $_POST['pass']));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(($_POST['user'] == $result['username']) && $_POST['pass'] == hash("sha256",$result['password'])) {
echo "Your username and password matches what I have! <html><br /></html>";
} else {
echo "Your username and password DOES NOT matches what I have! <html><br /> </html>";
}
}
?>
You've got one concept of password storage backwards: your code compares $_POST['pass'] to the hash of the string in the database. So users are required to enter a SHA256 hash of their password? And you store plaintext password in the database? I don't think so.
It should be the other way around. You allow users to enter their password, then you hash the string they enter. Then compare that to what's stored in the database, which should also be a hashed string.
$pass_hash = hash("sha256", $_POST["pass"]);
$stmt = $db->prepare("SELECT * FROM registration WHERE username = :username AND password = :password");
$stmt->execute(array("username" => $_POST['user'], "password" => $pass_hash));
You don't have to use an if() to test the results. Just test if the query returns zero rows, or not. If it returns any rows, then you found a match.
Also don't assume fetch() returned a row. If there was no row, it returns NULL, so using that row as an associative array will throw an error. Test to see if the row is non-null before dereferencing it.
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// username and password matched a row
echo "Your username and password matches what I have! <html><br /></html>";
} else {
// no matching username
echo "Your username and password DOES NOT matches what I have! <html><br /> </html>";
}
Here's an alternative variation I prefer: I just look for a row matching the username, and I return the hashed password string. Then I compare in application code. This way I can tell if they gave a legitimate username, but the wrong password. You don't necessarily want to reveal that to the user, but you might want to track it in your app so if someone is trying dozens of wrong passwords for the same username, you could lock the username or log an alert for the operator or something.
$stmt = $db->prepare("SELECT password FROM registration WHERE username = :username");
$stmt->execute(array("username" => $_POST['user']));
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$pass_hash = hash("sha256", $_POST["pass"]);
if ($pass_hash == $row['password']) {
echo "Your username and password matches what I have! <html><br /></html>";
} else {
// username exists, but wrong password
echo "Your username and password DOES NOT matches what I have! <html><br /> </html>";
}
} else {
// no matching username
echo "Your username and password DOES NOT matches what I have! <html><br /> </html>";
}
I have a login for my site. Below shows the registration page. The emailaddress is their username. How do create an error message alert if an # symbol and . has not been inserted into the username(emailaddress) field?
<?php
// Check if he wants to register:
if (!empty($_POST[emailaddress]))
{
// Check if passwords match.
if ($_POST[password] != $_POST[password2])
exit("Error - Passwords don't match. Please go back and try again.");
// Assign some variables.
$date = mktime("d - m - Y");
$ip = $_SERVER[REMOTE_ADDR];
require_once("config.php");
// Register him.
$query = mysql_query("INSERT INTO neworders
(emailaddress, firstname, surname, password, datereg, ip)
VALUES ('$_POST[emailaddress]','$_POST[firstname]','$_POST[surname]','$_POST[password]','$datereg','$ip')")
or die ("Error - Couldn't register user.");
echo "Welcome $_POST[username]! You've been successfully reigstered!<br /><br />
Please login <a href='login.php'><b>here</b></a>.";
exit();
}
?>
You should probably use a more robust solution to validate emails. Use PHP's filter_var() function with the FILTER_VALIDATE_EMAIL flag.
$validEmail = filter_var($email, FILTER_VALIDATE_EMAIL);
Of course, this is just for validating the email. If you're inserting it into a database, use that database's escape mechanism for strings or use bound queries.
Use the function at the bottom of this page:
http://www.linuxjournal.com/article/9585
You can check if a string has characters in it with the stristr() php function (This is not the ideal solution, but just very simply checks if characters in a string exist like you described. Using filter_var as described below is a better solution).
So to do what you are asking you could do something like:
if(!(stristr($_POST['emailaddress'], '#') && stristr($_POST['emailaddress'], '.')) {
echo 'Email not valid';
exit(1);
}
Something else you could do is use the prebuilt php filter_var function to do this: http://php.net/manual/en/function.filter-var.php
if(!filter_var($_POST['emailaddress'],FILTER_VALIDATE_EMAIL)) {
echo 'Email not valid';
exit(1);
}
You can also use regex pattern matching if you want. I would also advise to do some sort of cleaning (mysql_real_string_escape) on the $_POST['emailaddress'] field, if you are inserting it into a database.
ive created a form and im using php to check if the username exists in the database, if it is then the form will not submit and echo an alter that the username has already been taken, if i fill the form out and submit it with a name thatn i know is in the database, i get the error saying that the username already exists, but i also get the text that says.. Thank you for signing up
basically its showing the error correctly but it still submitting all the for data to the database
can you see anything in my code thats causing this??
//Check to see if the username is already taken
$query = "SELECT * FROM clients";
$result = mysql_query($query) or die(mysql_error()); // Get an array with the clients
while($row = mysql_fetch_array($result)){ // For each instance, check the username
if($row["username"] == $username){
$usernametaken = true;
}else{$usernametaken = false;}
}
// If the username is invalid, tell the user.
// Or else if the password is invalid, tell the user.
// Or else if the email or PayPal address is invalid, tell the user.
// Else, if everything is ok, insert the data into the database and tell
// the user they’ve successfully signed up.
if($usernametaken)
{
echo "That username has been taken.";
}
if(!preg_match('/^[a-zA-Z0-9]+$/', $username ))// If our username is invalid
{
echo "The username can only contain letters or numbers"; // Tell the user
}
else if(!preg_match('/^[a-zA_Z0-9]+$/', $password ))// If our password is invalid
{
echo "The password can only contain letters or numbers"; // Tell the user
}
// If our email or PayPal addresses are invalid
else if(!preg_match("/^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/", $email))
{
return "The email or PayPal address you entered is invalid."; // Tell the user
}
else{
// Inserts the data into the database
$result = mysql_query("INSERT INTO clients (client_ID, username, password, email, paypal)"."VALUES ('', '$username', '$pw', '$email', '$paypal')");
echo "Thank you for signing up.";
}
?>
You need to break out of your function if the username is no good. You could add an else if before the preg match if you don't want your last line to run. Basically your program flow is
//if username taken
//if bunch of cases
//else add client
There is nothing separating your two if statements.
Your SQL statement is a bear too. You are looping through every client in your db to see if it is a duplicate. Just add a where statement
$query = "SELECT * FROM clients WHERE clientName = '$clientName'";
You don't have anything to tell the script to stop executing if it finds that the username is taken. Restructure your if-else statement like this:
if($usernametaken)
{
echo "That username has been taken.";
} else {
// If username is not taken...
}
Instead of using several else ifs may I recommend using exceptions for this situation.
Demonstration:
<?php
try
{
if ($usernametaken) throw new Exception('That username has been taken.');
// If we've reached here we know data has been checked properly
$result = mysql_query("INSERT INTO clients (client_ID, username, password, email, paypal)"."VALUES ('', '$username', '$pw', '$email', '$paypal')");
echo "Thank you for signing up.";
}
catch (Exception $e)
{
echo $e->getMessage();
}
?>