无法回显某些PHP变量

时间:2019-02-25 16:05:58

标签: php

我正在尝试接受来自表单的输入并将某些元素回显到html页面中。但是由于某些原因,我定义的变量没有显示出来。

这是我检索表单并设置变量的代码:

<?php 
$firstName = $lastName = $email = $phone = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
    $firstName = test_input($_POST['firstName']);
    $lastName = test_input($_POST['lastName']);
    $email = test_input($_POST['email']);
    $phone = test_input($_POST['phone']);
    $message = test_input($_POST['message']);
}

function test_input($data){
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
} ?>

这是我使用的表格:

     <div style="width: 50%; margin:0 auto;border-style: solid;">
        <?php echo $_POST["message"]; ?>
        <?php echo $message; ?>
        <form action="<?php echo htmlspecialchars($_SERVER["$_PHP_SELF"]) ?>" method="POST" id="contactForm">
            First Name: <input type="text" id="firstName" name="firstName"><br>
            Last Name: <input type="text" id="lastName" name="lastName"><br>
            Email: <input type="text" id="email" name="email"><br>
            Phone: <input type="text" id="phone" name="phone"><br>
            Leave a message:<br>
            <textarea id="message" name="message"></textarea><br>
            <input type="submit">   
        </form>
    </div>

$ _ POST ['message']正确回显,但是我无法弄清楚为什么我在PHP代码中设置的$ message变量不会回显。我在这里做错了什么?

2 个答案:

答案 0 :(得分:3)

test_input不返回任何内容,因此$message的内容为NULL。 $ message 可能正在被回显,它在回显“无”。

答案 1 :(得分:2)

您的函数不返回任何内容。

这里是更新的代码。

function test_input($data){
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
相关问题