我试图阻止用户在除了a-z(A-Z),0-9和空格之外的用户名框中放置任何字符。以下是开始的HTML:
$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");
非常自我解释,对吧?
这里是关于register.php的PHP:
stripslashes
当我尝试使用" test#@!?* ^' /"()"等用户名创建用户时,preg_match函数不会工作。它不是重定向回登录/注册页面(auth.php),而是将用户添加到数据库并将我重定向到主页(index.php)。
我也尝试过/ ^ [a-z0-9 .-] + $ / i来获取preg_match中的参数,但这些参数都没有。
只是旁注,我出于安全考虑不使用此功能,我使用mysql_real_escape_string
和olimex a13
AFTER preg_match。
任何想法,或更好的方式只允许a-z(A-Z),0-9和空格?我一直试图解决这个问题几个小时,但无济于事。谢谢!
答案 0 :(得分:1)
使用此preg_match代码仅允许Letters(包括大写),Numbers和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");
}
答案 1 :(得分:1)
由于插入符号(^
)位置:
/[^a-zA-Z0-9[:space:]]+$/
↑
在这个位置,插入符号在方括号内取消了以下模式。实际上,您的模式搜索任何不 a-zA-Z0-9...
。
要将字符串与仅字母数字字符和空格匹配,您必须在模式开头处移动插入符号。在这个位置,插入符号表示“字符串的开头”:
/^[a-zA-Z0-9[:space:]]+$/
↑
但您也可以简化模式,并将[:space:]
替换为真实的空格([:space:]
和\s
匹配换行符,制表符等... 1 < / SUP>)。试试this regular expression:
/^[A-z0-9 ]+$/
解决方案是die()
。
如果字符串与模式不匹配,则执行以下代码:
$message = "Your username may only contain letters, numbers and spaces";
$_SESSION['error'] = $message;
header("Location:auth.php");
发送标头不会中断脚本,因此会执行剩余的代码并加载最后发送的标头(Location:index.php
)。
发送标题后强制脚本终止:
header("Location:auth.php");
die();
1 来自PHP documentation:“”空格“字符是HT(9),LF(10),FF(12),CR(13)和空格(32) 。但是,如果发生特定于语言环境的匹配,则代码点在128-255范围内的字符也可以视为空白字符,例如,NBSP(A0)。“
答案 2 :(得分:0)
答案 3 :(得分:0)
感谢Ghulam解决了这个问题......虽然他写的代码错了所以我的逻辑非常好,所以我已经更新了它。
还使用fusion3k的die();
方法更新了我的答案,以确保代码完全完成。
$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");
}
我们将$passed
设置为0开始。
如果$username
只包含字母a-z(A-Z),0-9和空格,那么我们将$passed
设置为1,因为它已通过preg_match检查。
如果$username
包含除此之外的任何其他字符(@,%,^ etc),则我们将$passed
变量保留为0。
如果$passed
为0,则用户名为无效,因此请将用户返回到注册/登录页面(auth.php)并向其发送错误消息。
如果$passed
为1,则用户名为有效,以便我们可以将用户添加到数据库并将其返回主页。
die();
用于确保代码在发送标头重定向后停止读取/运行。页面可能会重定向,但用户仍可以添加到数据库中!