PHP检查php 5+中$ _POST是否为空

时间:2015-04-30 13:57:43

标签: php login-script

我想尝试检查一个$ _POST数组是否为空但我在谷歌搜索和搜索youtube的2天内没有找到任何解决方案。 这是我的基本代码:

 if(isset($_POST['username']) and $_POST['password']){

    $username = $_POST['username'];
    $password = $_POST['password'];

    foreach($username as $user){
        if(empty($_POST[$user])){
            $error = "you need to fill in your username";
        }
    }
    foreach($password as $pass){
        if(empty($_POST[$pass])){
            $error = "you need to fill in your password";
        }
    }
    if(isset($error)){
        echo $error;

        ?>
        <br> <br>
    <?php
    }
        }

谢谢大家

4 个答案:

答案 0 :(得分:2)

要检查$_POST是否为空,您需要做的只是

if(empty($_POST)) {

答案 1 :(得分:0)

我不确定您为什么要处理一系列用户名和密码。也许这就是你正在寻找的东西:

mt2[;;;]25 or ht2[;;;]25

无论如何,您应该使用if(isset($_POST['username']) and $_POST['password']){ $error_msg = "Please provide username and password!"; if(isset($_POST['username'])) $username = $_POST['username']; if(isset($_POST['password'])) $password = $_POST['password']; if( !isset($username) || !isset($password) ) echo $error_msg; else{ //Do something ? } } 检查变量是否存在,并且可以使用isset检查变量是否为空。

答案 2 :(得分:0)

您可以使用if(!empty($_POST['username']))(非空),if(isset($_POST['username']))或简称if($_POST['username']),即:

empty()

if(!empty($_POST['username']) and !empty($_POST['password'])){
  $username = $_POST['username'];
  $password = $_POST['password'];
}

注意:empty()是检查POST var是否包含值的最安全方法。

isset()

if(isset($_POST['username'], $_POST['password'])){
  $username = $_POST['username'];
  $password = $_POST['password'];
}

注意:isset()只返回true空格。

为了简化您的代码,我建议如下:

if($_POST['username'] and $_POST['password']){
  $username = $_POST['username'];
  $password = $_POST['password'];
}

注意:它也会返回true只有空格。

答案 3 :(得分:0)

  

我想尝试检查$ _POST数组是否为空

您的代码存在以下问题:

if(empty($_POST[$user])){

您误解了函数foreach

你需要这样:

if(isset($user)){

这都是基于你想要检查数组的值是否为空。如果你还想要其他任何东西,你根本就不够清楚。

您已经使用此部分检查阵列是否为空:

if(isset($_POST['username']) and $_POST['password']){
相关问题