2011-01-23 40 views

回答

5
if (strpos($_POST['password'], ' ') !== false) { 
    echo "Don't try to write space."; 
} 
0

这将做的工作:

if (strpos($_POST['password'], ' ') !== false) { 
    echo "Don't try to write space."; 
} 

不过...。那泰(看上面),得到arguement是一个好的。 您不应限制用户在其密码中使用空格和其他字符。

$upass = $_POST['password']; 
    $usalt = substr(md5(uniqid(rand(), true)),0,7); 
    $upasshash = sha1(md5($upass).$usalt);  

现在将用户信息存储在数据库中。 为了安全起见,请清理$ _POST ['用户名']。 同样使用修剪来清理不必要空间的字段。

$upass = trim($_POST['password']); 
    $uname = mysql_real_escape_string(trim($_POST['username'])); 
    //Get the from data. 
    $usalt = substr(md5(uniqid(rand(), true)),0,7); 
    $upasshash = sha1(md5($upass).$usalt); 
    //Salt for extra security (prevent attackers from using rainbow tables) 

    $sql = " INSERT INTO users (uname, upasshash, usalt) 
      VALUES ('$uname', '$upasshash', '$usalt');"; 
    mysql_query($sql); 

一个好处是,你不会在密码字段的数据库中创建开销。 $upasshash长度为40个字符。

更新: 这是一种登录用户的方式。

$mysqlcon = dbconnect(); 
$sql = "SELECT * FROM users WHERE uname = '$unamein';"; 
$result = mysql_query($sql); 
if(mysql_num_rows($result) == 1){ //Does the user exists and is it only 1 user? 
//Yes 1 match exacly 
    $fetch = mysql_fetch_assoc($result); 
    if(sha1(md5($upassin).$fetch['usalt']) == $fetch['upasshash']){ //Are the password hashes equal? 
    //Yes the hashes are equal 
     $_SESSION['check'] = true; 
     $_SESSION['uid'] = $fetch['uid']; 
     $_SESSION['uname'] = $fetch['uname']; 
     $message = 'Login succeded!';       
    }else{ 
    //NO the hashes ar not equal 
     $message = 'Wrong password and/or username.'; 
    } 
mysql_close($mysqlcon); 
}else{ 
// USER doest exist. 
    $message = 'Wrong password and/or username.'; 
} 

出于安全原因,请不要告诉他们他们错误填写了哪个字段。

0

您还可以在JavaScript中添加支票以提高用户体验(比服务器往返时间更快的响应时间)。如果你使用这条路线,不要完全依赖它,因为用户可能禁用了JavaScript,并且还在PHP中添加了一个检查。

<html> 
<head> 
<title>JavaScript Form Validation</title> 
<script type='text/javascript'> 
function validate() { 
    var pass = document.myForm.passwd.value; 
    for (var i = 0; i < pass.length; i++) { 
     if (pass.charAt(i) == ' ') { 
      alert("Please don't use spaces in the password"); 
      document.myForm.login.disabled = true; 
      return; 
     } 
    } 
    document.myForm.login.disabled = false; 
} 
</script> 
</head> 
<body> 

<form method='post' name='myForm'> 

<input type='password' name='passwd' id='passwd' onblur='validate()'/> 
<input type='submit' name='login' id='login'/> 

</form> 

</body> 
</html>