如何验证我的表单是空的,并提交显示在PHP中的错误?

时间:2017-08-01 08:13:29

标签: php

我是php新手。我的表单工作正常,但即使它是空的并提交,它也会显示成功的消息。

如何在表单提交为空时显示错误消息?

以下是代码:

Waiting client connection...  # a client send a HTTP request
client.c:accept_request() is called
client.c:handle_request() is called
asdf.c:func1() is called
fdsa.c:func2() is called
response.c:send_response() is called
Waiting client connection...

谢谢

1 个答案:

答案 0 :(得分:0)

这很容易,你应该自己找到它;-) 我添加了一个空eMail字段的检查,然后再次显示errorMessage和表单。

if(empty($_POST['submit']) === false) {

    if(empty($_POST['email'])) {
        echo 'Please enter an email to add in the email field!';
        showForm();
    } else {

        $email = htmlentities(strip_tags($_POST['email']));

        $logname = 'email.txt';
        $logcontents = file_get_contents($logname);

        if(strpos($logcontents,$email)) {
            die('You are already subscribed.');
        } else {
            $filecontents = $email.', ';
            $fileopen = fopen($logname,'a+');
            $filewrite = fwrite($fileopen,$filecontents);
            $fileclose = fclose($fileopen);
            if(!$fileopen or !$filewrite or !$fileclose or '') {
                die('Error occured');
            } else {
                echo 'Your email has been added.';
            }
        }   
    }
} else {
    showForm();
}