我目前正在使用我在网上找到的修改版本的登录脚本。 任何人都可以提出一些方法将代码模块化为函数吗?
以下是登录页面的代码:
<?php
include("db.php");
include("login_fns.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
$password=md5($password);
$sql="SELECT * FROM client_login WHERE Username='$username' and Password='$password'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row = mysql_fetch_array($result);
$client_ref = $row['Client_ref'];
$user_level = $row['user_level'];
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
$_SESSION['user_level'] = $user_level;
$_SESSION['client_ref'] = $client_ref;
$_SESSION['user'] = $username;
if ($user_level == '1') {
header('Location: admin.php');
} else {
header('Location: myaccount.php');
}
}
else
{
echo "Error logging in!";
}
}
?>
<form action="login.php" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />
<label>Password :</label>
<input type="password" name="password"/><br/>
<input type="submit" value=" Login "/><br />
</form>
理想情况下,我想要一个用户帐户搜索功能和会话设置功能。我之前尝试将此代码的代码段复制到一个单独的php函数文件中,但它似乎不起作用。
答案 0 :(得分:0)
您如何看待这个? :)
<?php
function checkLogin($username, $password) {
global $bd;
$returnArray=array();
$username=mysqli_real_escape_string($bd, $username);
$password=md5($password);
$getUser=mysqli_query($bd, "SELECT `Client_ref`,`user_level` FROM client_login WHERE Username='$username' and Password='$password'");
$arrayUser=mysqli_fetch_array($getUser);
if(mysqli_num_rows($getUser) == 0)
{
$returnArray['error']='true';
$returnArray['errormsg']='User not found in the database.';
return $returnArray;
}
$returnArray['Client_ref']=$row['Client_ref'];
$returnArray['user_level']=$row['user_level'];
return $returnArray;
}
?>
<?php
include("db.php");
include("login_fns.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$username=$_POST['username'];
$password=$_POST['password'];
$loginArray=checkLogin($username, $password);
if(!isset($loginArray['error']))
{
$_SESSION['user_level'] = $loginArray['Client_ref'];
$_SESSION['client_ref'] = $loginArray['user_level'];
$_SESSION['user'] = $username;
if($loginArray['user_level'] == '1')
{
header('Location: admin.php');
}
else
{
header('Location: myaccount.php');
}
}
else
{
echo "Error logging in!";
echo "The detailed error message is: ".$returnArray['errormsg'];
}
}
?>
<form action="login.php" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />
<label>Password :</label>
<input type="password" name="password"/><br/>
<input type="submit" value=" Login "/><br />
</form>