我为一个有两个登录表单的网页编写了一个非常简单的PHP登录脚本,只是想知道是否有任何方法可以对其进行优化(即在函数中包装所有以处理这两个登录) 。非常感谢任何想法!
session_start();
require_once("resources/php/connection.php");
// PM login
if(isset($_POST['pmsubmit']))
{
$pmname = $_POST['pmname'];
$pmpass = $_POST['pmpass'];
// check if password matches the one in the table
$query = $pdo->prepare("SELECT * FROM db_pass WHERE pass = :pass");
$query->execute(array(":pass" => $pmpass));
// if there is a match then we log in the user
if ($query->rowCount() > 0)
{
// session stuff
$_SESSION['pmname'] = $_POST['pmname'];
// refresh page
header( 'Location: pm/index.php' ) ;
}
// if there is no match then we present the user with an error
else
{
echo "error";
exit;
}
}
// TS login
if(isset($_POST['tssubmit']))
{
$dept = $_POST['dept'];
$tspass = $_POST['tspass'];
// check if password matches the one in the table
$query = $pdo->prepare("SELECT * FROM db_pass WHERE pass = :pass");
$query->execute(array(":pass" => $tspass));
if ($query->rowCount() > 0)
{
// session stuff
$_SESSION['dept'] = $_POST['dept'];
// refresh page
header( 'Location: ts/index.php' ) ;
}
// if there is no match then we present the user with an error
else
{
echo "error";
exit;
}
}
答案 0 :(得分:1)
如果你想要......你可以尝试这样的事情。
if(isset($_POST['pmsubmit']))
{
LoginSubmit('pm', 'pmname', 'pmpass');
}
if(isset($_POST['tssubmit']))
{
LoginSubmit('ts', 'dept', 'tspass');
}
function LoginSubmit($pm_or_ts, $the_name_input, $the_pass_input)
{
$the_name = $the_name_input;
$posted_name = $_POST[$the_name];
$posted_pass = $_POST[$the_pass_input];
// check if password matches the one in the table
$query = $pdo->prepare("SELECT * FROM db_pass WHERE pass = :pass");
$query->execute(array(":pass" => $posted_pass));
// if there is a match then we log in the user
if ($query->rowCount() > 0)
{
// session stuff
$_SESSION[$the_name] = $posted_name;
// refresh page
header( 'Location: ' . $pm_or_ts . '/index.php' ) ;
}
// if there is no match then we present the user with an error
else
{
echo "error";
exit;
}