//登入 function login() { global $db; $email = $db->real_escape_string($_POST['email']); if (empty($email)) { throw new Exception("Eamil為必填!"); } $email = filter_var($email, FILTER_VALIDATE_EMAIL); if (!$email) { throw new Exception("不合法的Email"); } $pass = isset($_POST['pass']) ? $_POST['pass'] : ''; $sql = "SELECT * FROM `users` where `email`='{$email}'"; $result = $db->query($sql); if (!$result) { throw new Exception($db->error); } $data = $result->fetch_assoc(); if (password_verify($pass, $data['pass'])) { $_SESSION['group'] = $data['group']; $_SESSION['name'] = htmlspecialchars($data['name'], ENT_QUOTES); $_SESSION['uid'] = $data['uid']; $_SESSION['email'] = htmlspecialchars($data['email'], ENT_QUOTES); } else { throw new Exception("登入失敗!"); } }
//登出 function logout() { unset($_SESSION['group']); unset($_SESSION['name']); unset($_SESSION['uid']); unset($_SESSION['email']); }
$name = $db->real_escape_string($_POST['name']); if (empty($name)) { throw new Exception("姓名為必填!"); } $email = $db->real_escape_string($_POST['email']); if (empty($email)) { throw new Exception("Eamil為必填!"); } $email = filter_var($email, FILTER_VALIDATE_EMAIL); if (!$email) { throw new Exception("不合法的Email"); } $pass = $db->real_escape_string($_POST['pass']); if (empty($pass)) { throw new Exception("密碼為必填!"); }
可簡化為
$name = clean_var('name', '姓名'); $email = clean_var('email', 'Eamil', FILTER_VALIDATE_EMAIL); $pass = clean_var('pass', '密碼');
參考答案:
//檢查並傳回欲拿到資料使用的變數 function clean_var($var = '', $title = '', $filter = '') { global $db; $clean_var = $db->real_escape_string($_REQUEST[$var]); if (empty($clean_var)) { throw new Exception("{$title}為必填!"); } if ($filter) { $clean_var = filter_var($clean_var, $filter); if (!$clean_var) { throw new Exception("不合法的{$title}"); } } return $clean_var; }