我想尝试检查 $_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
}
}
谢谢大家
要检查$_POST
是否为空,您需要做的就是
if(empty($_POST)) {
你的这部分代码很奇特:
foreach($username as $user){
if(empty($_POST[$user])){
$error = "you need to fill in your username";
}
}
据说要得到$username
的每个数组元素。然后检查元素是否为空。如果$username
有 0 个元素,那么它永远不会进入该循环。您不会看到该错误消息。然而,这里有一个更深层次的担忧。编写此代码时期望$_POST['username']
和$_POST['password']
是数组。几乎可以肯定情况并非如此。
相反,您可以使用array_key_exists
:
if( !array_key_exists('username',$_POST) )
{
$error = "you need to fill in your username";
}
作为侧面安全问题,我真的希望您不要通过$_POST
将密码信息存储为纯文本。您不希望该信息被任何一方拦截。
我想尝试检查 $_POST 数组是否为空
代码的问题在于这一部分:
if(empty($_POST[$user])){
你误解了每个函数
你需要有一个像这样的 if:
if(isset($user)){
这完全基于您要检查数组的值是否为空。如果你想要别的,你根本不够清楚。
您已经在检查以下部分的数组是否为空:
if(isset($_POST['username']) and $_POST['password']){
我不确定为什么要处理一系列用户名和密码。也许这就是你要找的:
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
来检查变量是否存在,您可以使用 empty
来检查变量是否为空。
if(!empty($_POST['username']))
(不为空),if(isset($_POST['username']))
或简单地使用if($_POST['username'])
,即:
空()
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
。