Im trying to do some preg match to make my script more secure, but whatever i type in username/realname i get error... where am i going wrong here?
$unpreg = $_POST["username"];
$empreg = $_POST["email"];
$rnpreg = $_POST["realname"];
$error = false;
if(preg_match("/[^\p{L}\p{N}_\-\.]+/iu','",$unpreg) || (filter_var($empreg, FILTER_SANITIZE_EMAIL)) || (preg_match("/[^\p{L}\s]+/u",$rnpreg))) {
$error = true;
}
if(!$error) {
$sql = "INSERT INTO Users (UserName, Email, Password,Real_Name) VALUES (:username, :email, :password, :realname)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':username',$unpreg);
$stmt->bindParam(':realname',$rnpreg);
$stmt->bindParam(':email', $empreg);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
$stmt->execute();
$message = 'Successfully created new user';
}
else {
$message = 'Error, Something went wrong.';
}
Basically for unpreg i want to allow a-ö 0-9 -_ and for rnpreg a-ö - and space
EDIT: if i remove (filter_var($empreg, FILTER_SANITIZE_EMAIL))
it works... how do i implemend that without breaking it?
The ','
in the first regex are an error and must be removed. Then, you need o use FILTER_SANITIZE_EMAIL
while you need FILTER_VALIDATE_EMAIL
to validate the email. And you need to negate the filter_var
since you follow negated logics in your if
.
Use
if(preg_match("/[^\p{L}\p{N}_.-]+/iu",$unpreg) || !filter_var($empreg, FILTER_VALIDATE_EMAIL) || preg_match("/[^\p{L}\s]+/u",$rnpreg))
So, the error will be returned if a [^\p{L}\p{N}_.-]+
pattern is found, or the email is not valid or if [^\p{L}\s]+
pattern is matched.