-1

我已经为带有两个登录表单的网页编写了一个非常简单的 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;
    }
}
4

1 回答 1

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;
  }
于 2013-02-02T00:06:00.553 回答