如何在仅使用 PHP 发布后保留 textarea 表单值

Posted

技术标签:

【中文标题】如何在仅使用 PHP 发布后保留 textarea 表单值【英文标题】:How to keep textarea form values after post only using PHP 【发布时间】:2020-10-17 09:38:08 【问题描述】:

我正在尝试为正在开展新业务的儿子设计一个页面,我需要一些有关两个组件的帮助。我是新手,所以我已经包含了完整的页面代码,还有很多参考资料,包括以前的 *** 帖子,所以希望这可能有助于获得反馈:

表单输入全部显示在 $_POST 上,但是 textarea 总是被清除。所有验证都适用于输入,textarea 卫生也适用。表单在验证时成功输入电子邮件。

<?php
    # 06contact.php: This is reCAPTCHA v3. 
    # reCaptcha Reference: https://www.phptreepoint.com/google-recaptcha-v3-in-php/
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <?php
            # This meta is for the sticky element to work
            # Source: https://www.w3schools.com/howto/howto_css_sticky_element.asp
        ?>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    
        <link href="/styles/css/mydomain.css" rel="stylesheet" type="text/css">
        <title>mydomain.com: Contact Us</title>
        <script src="https://www.google.com/recaptcha/api.js?render='domain_public_key'"></script>
    </head>
    
    <body>
        <div id="wrapper">
            <div class="container_top">
                <?php include ('includes/header.php'); ?>
                <?php include ('includes/nav.php'); ?>
            </div>
            
            <div class="container_body">
                <div class="container_bdr container_form">
                    <h2 align="center">mydomain.com - Form</h2>
                    <form action="06contact.php" method="post">
                        <fieldset>
                            <legend for="fullname">First and Last Names</legend>
                            <input name="fullname" type="text" align="left" value="<?php if (isset($_POST['fullname'])) echo $_POST['fullname']; ?>" placeholder="insert first and last names here" required>
                        </fieldset>
                        <fieldset>
                            <legend for="email">Email</legend>
                            <input name="email" type="email" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" placeholder="insert email address here" required>
                        </fieldset>
                        <fieldset>
                            <legend for="telephone">Telephone</legend>
                            <?php # example input mask
                            # https://***.com/questions/17980061/how-to-change-phone-number-format-in-input-as-you-type?>
                            <input name="telephone" type="tel" maxlength="15" value="<?php if (isset($_POST['telephone'])) echo $_POST['telephone']; ?>" placeholder="number starting with area code" required>
                        </fieldset>
                        
                        <fieldset>
                        <?php 
                            #id or name tag on forms or both?
                            # Reference: https://***.com/questions/1397592/difference-between-id-and-name-attributes-in-html
                            # Reference: https://codepen.io/geoffmuskett/pen/uldmJ (for text counter script, see script at end of body tag)
                        ?>
                            <legend for="message">Message</legend>
                            <textarea id="message" name="message" type="text" maxlength="200" 
                            value="<?php 
                            #if (isset($_POST['textareaChars'])) echo $_POST['textareaChars']; old reference changed to 'message'.
                            # Next line code textarea clears on submit:
                            if (isset($_POST['message'])) echo $_POST['message'];
#                           if (isset($_POST['message'])) echo $message;
                            
                            # Reference: https://***.com/questions/5198304/how-to-keep-form-values-after-post
                            # value=    "echo isset($_POST['myField1']) ? $_POST['myField1'] : ''; ';' added to end by RH
                            # Next line code textarea clears on submit:
                            #echo isset($_POST['message']) ? $_POST['message'] : '';
                            
                            # Reference: https://***.com/questions/2246227/keep-values-selected-after-form-submission (see $_POST example)
                            #if (isset($example) && $example=="a") echo "selected";
                            # Next line code textarea clears on submit:
                            #if (isset($message)) echo $message;
                            
                            # Reference: https://***.com/questions/18653137/keeping-textarea-content-after-a-form-submission
                            # if(isset($_POST['textarea1']))  echo htmlentities ($_POST['textarea1']);
                            # Next line code textarea clears on submit:
                            #if(isset($_POST['message']))  echo htmlentities ($_POST['message']); 
                            ?>" placeholder="Please insert your message here such as your zip code and the size of your pool in total gallons if you know it." required></textarea>
                        <counter><span id="chars">200</span> characters remaining.</counter>
                        </fieldset>


            <?php
                #if ($_POST['submit']) 
                if (isset($_POST['submit'])) 
                    $fullname = $_POST['fullname'];
                    $email = $_POST['email'];
                    $telephone = $_POST['telephone'];
                    $message = $_POST['message'];
                
                    if (empty($fullname)) 
                        $fullnameErr = "Please insert your full name to continue!";
                        echo $fullnameErr;
                    // check if $fullname only contains letters and whitespace
                     else if (!preg_match("/^[a-zA-Z ]*$/",$fullname)) 
                        $fullnameErr = "For full name only letters and space allowed";
                        echo $fullnameErr;
                     else if (empty($email)) 
                        $emailErr = "Please insert your email address to continue!";
                        echo $emailErr;
                    // validate $email
                     else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) 
                        $emailErr = "Invalid email format. Please insert a valid email address to continue";
                        //    echo $emailErr;
                        echo $emailErr;
                    // validate $telephone:
                     else if (empty($telephone)) 
                        $telephoneErr = "Please insert your telephone number";
                        echo $telephoneErr;
                    // check if $telephone only contains numbers and whitespace
#                else if (!preg_match('/^\d10$/',$telephone))       //allow 10 digits.
#                else if (!preg_match('/^[+0-9. ()-]*$/',$telephone)) 
                     else if (!preg_match('/^[0-9]10$/',$telephone))  //allow 10 digits.
#                else if (!preg_match('/^[0-9]*$/',$telephone)) 
                        $telephoneErr = "For telephone only numbers are allowed. Should be 10 digits including area code.";
                        echo $telephoneErr;
                
                    // collect $message
                    
                    # strip message of harmful characters
                    # preg_replace / sanitize
                    # https://***.com/questions/19167432/strip-bad-characters-from-an-html-php-contact-form (c2013: only 1 answer)
                    # https://***.com/questions/129677/how-can-i-sanitize-user-input-with-php (c2014: htmlspecialchars?)
                    # https://wp-mix.com/php-sanitize-form-data/
                        
#                    else if (empty($message))                            | not necessary as $message
#                       $message = "Default: Please contact me.";       | is 'required' on form.

#                    else if (!empty($message))                                                               | code doesn't work
#                       $message = htmlentities(strip_tags($message), ENT_QUOTES, 'UTF-8');     | if enabled here
                                    
                     else 
                        # See also: filter_var($message, FILTER_SANITIZE_STRING);
                        # Clean up textarea message:
                        $message = htmlentities(strip_tags($message), ENT_QUOTES, 'UTF-8');
                        
                        $token  = $_POST['token'];
                        $action = $_POST['action'];
                
                        $curlData = array(
                            'secret' => 'domain_private_key',
                            'response' => $token
                        );
                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
                        curl_setopt($ch, CURLOPT_POST, 1);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($curlData));
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        $curlResponse = curl_exec($ch);
        
                        $captchaResponse = json_decode($curlResponse, true);
        
                        if ($captchaResponse['success'] == '1' && $captchaResponse['action'] == $action && $captchaResponse['score'] >= 0.5 && $captchaResponse['hostname'] == $_SERVER['SERVER_NAME']) 
                            echo 'Form Submitted Successfully';
                            
                            
                            # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! NEXT LINE FOR TESTING ONLY !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                            echo '<br>' . $fullname . ' / ' . $telephone . ' / ' . $email . ' / ' . $message;
                            
                            
/*                          # Email form submission reference:
                            # Reference: https://learning.linkedin.com/blog/tech-tips/send-email-from-a-web-form-with-php
                            if (isset($success) && $success) 
                            #   echo 'Your message has been sent successfully.';
                                
                                # if (isset($_POST[['submit']))  #already set above.
*/                              $to = 'receive@email.com'; #edit as required.
                                $subject = 'mydomain.com: Message from website.';
                                $value = 'Fullname: ' . $fullname . "\r\n\r\n";
                                $value .= 'Email: ' . $email . "\r\n\r\n";
                                $value .= 'Telephone: ' . $telephone . "\r\n\r\n";
                                $value .= 'Message: ' . "\r\n" . $message . "\r\n\r\n";
                                #echo $value0 . $value1 . $value2 . $value3;
                                
                                $headers = "From: from@email.com \r\n";
                                $headers .= 'Content-Type: text/plain; charset=utf-8';
                                $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
                                if ($email) 
                                    $headers .= "\r\nReply-To: $email";
                                
                                $success = mail($to, $subject, $value, $headers);
                        
                    
                
            ?>

<?php # example response values:
/*  
        "success": true|false,      // whether this request was a valid reCAPTCHA token for your site
        "score": number             // the score for this request (0.0 - 1.0)
        "action": string            // the action name for this request (important to verify)
        "challenge_ts": timestamp,  // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
        "hostname": string,         // the hostname of the site where the reCAPTCHA was solved
        "error-codes": [...]        // optional
    
*/
?>

                        <input type="hidden" name="token" id="token" />
                        <input type="hidden" name="action" id="action" /> 
                        <br><br>
                        <input type="submit" name="submit" value="Submit Message">
                    </form>
                </div><!-- END: div class="container_bdr container_form" -->
            </div><!-- END: class="container_body" -->

            <div class="container_bottom">
                <?php include ('includes/footer.php'); ?>
            </div><!-- END div class="container_bottom" -->
        </div><!-- END div #wrapper -->

        <script src="https://www.google.com/recaptcha/api.js?render='domain_public_key'"></script>
        <script  src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function()
                setInterval(function()
                    grecaptcha.ready(function() 
                        grecaptcha.execute('domain_public_key', action: 'application_form').then(function(token) 
                            $('#token').val(token);
                            $('#action').val('application_form');
                        );
                    );
                , 3000);
            );
        </script>
        <script>
            var maxLength = 200;
            $('textarea').keyup(function() 
                var length = $(this).val().length;
                var length = maxLength-length;
                $('#chars').text(length);
            );
        </script>
    </body>
</html>

第二部分是textarea 验证。如果我将它包含在下面 的最后部分,否则如果 部分:-

// collect $message
.......
#                    else if (!empty($message))                                                               | code doesn't work
#                       $message = htmlentities(strip_tags($message), ENT_QUOTES, 'UTF-8');     | if enabled here
                                    
                     else 
                        # See also: filter_var($message, FILTER_SANITIZE_STRING);
                        # Clean up textarea message:
                        $message = htmlentities(strip_tags($message), ENT_QUOTES, 'UTF-8');

然后代码不起作用,我什至没有收到错误消息或成功消息。我只能通过将其移至最后的 else 部分来使其工作。这可能是必须的,但我不明白为什么。

我知道我的 if(empty($var)) 不需要,因为我现在在表单输入上使用 'required' 标记。

在此先感谢并祝贺利物浦成为英超冠军

【问题讨论】:

【参考方案1】:

textarea 不支持 valueplaceholder 属性。

你必须这样做---

** 更新 1: [用于在发生任何错误后显示 textarea 的输入值]

<textarea id="message" name="message" type="text" maxlength="200">

<?php 
    if (isset($_POST['textareaChars'])) echo $_POST['textareaChars'];
?>

</textarea>

** 更新 2:

问题:

由于 $message 不是空的,所以 else if 部分正在执行。它没有到达您程序的 else 部分。那就是问题所在。 因此,在这里您不需要任何 else if 部分来进行 $message 清理。您应该使用 else 部分输入清理作为以下代码..

if (isset($_POST['submit'])) 
    $fullname = $_POST['fullname'];
    $email = $_POST['email'];
    $telephone = $_POST['telephone'];
    $message = $_POST['message'];

    if (empty($fullname)) 
        $fullnameErr = "Please insert your full name to continue!";
        echo $fullnameErr;
    // check if $fullname only contains letters and whitespace
     else if (!preg_match("/^[a-zA-Z ]*$/",$fullname)) 
        $fullnameErr = "For full name only letters and space allowed";
        echo $fullnameErr;
     else if (empty($email)) 
        $emailErr = "Please insert your email address to continue!";
        echo $emailErr;
    // validate $email
     else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) 
        $emailErr = "Invalid email format. Please insert a valid email address to continue";
        //    echo $emailErr;
        echo $emailErr;
    // validate $telephone:
     else if (empty($telephone)) 
        $telephoneErr = "Please insert your telephone number";
        echo $telephoneErr;
     else if (!preg_match('/^[0-9]10$/',$telephone))  //
        $telephoneErr = "For telephone only numbers are allowed. Should be 10 digits including area code.";
        echo $telephoneErr;
                    
     else if (!empty($message))  
        $messageErr = "ERROR MESSAGE FOR $message"; 
     else 
        # IF EVERYTHING GOES WELL THEN THIS PART WILL EXECUTE
        # SANITIZATION OF YOUR ALL ALL INPUTS SHOULD BE HERE
        $message = htmlentities(strip_tags($message), ENT_QUOTES, 'UTF-8');
        echo $message;

        #REST OF THE PROGRAM ......
    

谢谢。

【讨论】:

我的占位符文本确实显示在我的文本区域中。我也尝试了您建议的代码,请参阅代码的注释部分。它仍然不会在表单提交时显示用户输入。 @guvna 抱歉,我部分遇到了问题。现在我编辑了我的答案。希望它会帮助你。谢谢。 The else 部分正在工作,因为表单结果已成功通过电子邮件发送。在原始代码上, else if 应该像使用的代码那样工作,如果 $message 不为空 (!empty($message)。由于 textarea 是必填字段,因此将始终提示用户输入,所以没有在继续执行脚本的其余部分之前需要错误消息。 Somen 起初我并没有猜到您对“textarea 不支持价值”的评论,但我想我现在明白了。我从开始 textarea 标记中删除了“值”设置,并将其放在结束 textarea 标记之前: 。这行得通。

以上是关于如何在仅使用 PHP 发布后保留 textarea 表单值的主要内容,如果未能解决你的问题,请参考以下文章

如何在html textarea POST数据中保留换行符

使用php提交后将表单数据保留在字段内

如何使用 php 保留一些限制的空格?

如何使用 php 在仅一列中添加编辑和删除按钮?

如何在仅运行 10 秒的程序上设置右键单击->选项->保留在 Dock 中?

HTML:如何在 textarea 中保留格式?