仅返回true或false(PHP)

时间:2014-12-25 00:28:53

标签: php function if-statement

我有这个PHP代码,在运行多个存储函数后应该只返回true或false,但遗憾的是它不能按预期工作。 我首先检查电子邮件验证,如果有效则返回true,如果无效,则返回false,然后我对用户名执行相同操作。

if($_SERVER['REQUEST_METHOD'] == 'POST') {

// Email is valid
if(checkmail($_POST['email'])) {
    $_SESSION['v_mail'] = $_POST['email'];
    $valid = true;} else { $valid=false; }

// username is valid
if(checkuser($_POST['username'],5,10)) {
    $_SESSION['v_username'] = $_POST['username'];
    $valid=true;} else { $valid=false; }

}

检查两者后,我只需要返回False或True。 我知道这是一个非常小的技巧,但我无法得到它。

2 个答案:

答案 0 :(得分:0)

试试这个:

if($_SERVER['REQUEST_METHOD'] == 'POST') {

// Email is valid
if(checkmail($_POST['email'])) {
    $_SESSION['v_mail'] = $_POST['email'];
    $valid = true;} else { $valid=false; }

// username is valid
if(checkuser($_POST['username'],5,10)) {
    $_SESSION['v_username'] = $_POST['username'];
    } else { $valid=false; } //and between the last $valid value

}

或者再次:

if($_SERVER['REQUEST_METHOD'] == 'POST') {

// Email is valid
if(checkmail($_POST['email'])) {
    $_SESSION['v_mail'] = $_POST['email'];
    $valid = true;} else { 
 $valid=false; return} //exit from the function if valid is false

// username is valid
if(checkuser($_POST['username'],5,10)) {
    $_SESSION['v_username'] = $_POST['username'];
    $valid=true;} else { $valid=false; }

}

答案 1 :(得分:0)

if(checkmail($_POST['email']) && checkuser($_POST['username'],5,10)) {
    $_SESSION['v_mail'] = $_POST['email'];
    $_SESSION['v_username'] = $_POST['username'];
    $valid = true;
} else {
    $valid = false;
}

对不起累了错过部分代码,但是我会稍微改变一下这个问题:

$isMail = (checkmail($_POST['email'])) ? $_SESSION['v_mail'] = $_POST['email'] : false;
$isUser = (checkuser($_POST['username'],5,10)) ? $_SESSION['v_username'] = $_POST['username'] : false;
$valid = $isMail && $isUser;

或将$_SESSION个变量移至checkmailcheckuser个函数,然后只需$valid = checkmail($_POST['email']) && checkuser($_POST['username'],5,10)