我在做php表单,而else语句只是被输出


I was doing php forms, and the else statement is only being outputted

这是代码-我不知道问题在哪里…

我的形式:

  <form action="process1.php" method="post" >   
    first name : <input type="text" name="first name" value="" />
    password : <input type="password" name="pasword" value= "" />
    <br/>
    <input type="submit" name="submit" value="submit" />
    </form>

process1.php

    <?php
    $users = array("abhishek","alan" ); # was doing to limit the users  
    if (firstname == $users ){
        $firstname = $_post['firstname'];
        $password  = $_post[ 'password'];
        echo "$firstname" . "and". "$password"; 
    }else { 
        echo "access denied";
    } 
     ?>

即使我输入abhishek或alan,输出也显示access denied:

Notice: Use of undefined constant firstname -  
assumed 'firstname' in F:'wamp'www'php_sandbox'process1.php on line 9     
access denied

我知道我不应该回答这个问题,因为它的质量如此之低-但它可能有助于解释给别人(一遍又一遍又一遍)

误差Notice: Use of undefined constant firstname - assumed 'firstname'再清楚不过了,firstname不是一个变量。您指的是$firstname,但您也意味着在使用它之前从POST数据定义它。

参见逐行注释:

$users = array("abhishek", "alan"); // Creates an array
if (firstname /* "firstname" */ == $users) { // You're comparing a string to an array
    $firstname = $_post['firstname']; // You're defining the variable after you've used it, assuming corrected above
    $password  = $_post[ 'password'];
    echo "$firstname" . "and". "$password"; // Here you're concatenating three strings needlessly
}else { 
    echo "access denied";
} 

更有效的代码是这样的,LbL:

$users = array("abhishek", "alan"); // Define array
$firstname = $_POST['firstname']; // Create $firstname from POSTed data
$password  = $_POST[ 'password']; // Create $password from POSTed data
if (!empty($firstname) && in_array($firstname, $users))
{ // Check if $firstname has a value, and also is IN the array
    echo "$firstname and $password";  // Variables are automatically placed in double quoted strings
} else {
    echo "access denied";
}

您还需要更正HTML输入字段,使其具有正确的名称:

first name : <input type="text" name="firstname" value="" />
password : <input type="password" name="password" value= "" />

我建议在继续之前阅读更多关于PHP/编程的知识,因为如果您在此基础上构建,您将很快拥有一个非常不安全的系统。

在您的表单中,您将输入命名为'firstname',但在您的php中,您将其搜索为'firstname'(空格)。

同时,将$_post改为$_post;在你的if子句中,你需要在名字后面加上$,并声明它。

形式
<form action="process1.php" method="post" >   
    first name : <input type="text" name="firstname" value="" />
    password : <input type="password" name="password" value= "" />
    <br/>
    <input type="submit" name="submit" value="submit" />
</form>
PHP

<?php
$firstname = $_POST['firstname'];
$users = array("abhishek","alan" ); # was doing to limit the users
if (in_array($firstname,$users) )
{
 $password  = $_POST['password'];
 echo "$firstname" . " and ". "$password";
}else {
 echo "access denied";
}
?>