dongshan4549 2018-10-19 16:53
浏览 28
已采纳

单击“提交”时,消息字段变空

I have combined PHP validation and PHPmailer, the code is working perfectly. The only problem I am facing now is whenever I click submit, the message "textarea" is getting empty, therefore I have to retype the whole message again. Example: if the name is wrongly entered and all other fields are OK, when you click submit it will show the warning message under the name field but the message will be coming empty, I hope I have delivered my message in a proper way. *I am using PHPmailer without composer.

index.php:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Event Axis</title>
        <link href="style.css" rel="stylesheet">
    </head>
    <body>
        <div class="container">
            <?php include('contact.php');?>
            <form id="contact" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                <fieldset>
                    <input class="form-control" placeholder="Your name" type="text" name="name" value="<?= $name ?>" tabindex="1">
                    <span class="error"><?= $name_error ?></span>
                </fieldset>
                <fieldset>
                    <input class="form-control" placeholder="Your Email Address" type="text" 
                        name="email" value="<?= $email ?>" tabindex="2">
                    <span class="error"><?= $email_error ?></span>
                </fieldset>
                <fieldset>
                    <input class="form-control" placeholder="Your Phone Number, ex: 1122334455" type="text" name="phone" value="<?= $phone ?>" tabindex="3">
                    <span class="error"><?= $phone_error ?></span>
                </fieldset>
                <fieldset>
                    <textarea class="form-control" placeholder="Type your message here" type="text" name="message" value="<?= $message ?>" tabindex="5"></textarea>
                    <span class="error"><?= $message_error ?></span>
                </fieldset>
                <fieldset>
                    <button name="submit" type="submit" id="contact-submit" data-submit="Sending.." value="">Submit</button>
                    <span class="success"><?= $success; ?></span>
                </fieldset>
            </form>
        </div>
    </body>
</html>

contact.php:

use PHPMailer\PHPMailer\PHPMailer; //You shall use the following exact namespaces no matter in whathever directory you upload your phpmailer files
use PHPMailer\PHPMailer\Exception;


// define variables and set to empty values
$name_error = $email_error = $phone_error = $message_error = "";
$name = $email = $phone = $message = $success = "";

if($_SERVER["REQUEST_METHOD"] == "POST") {

    if(empty($_POST["name"])) {
        $name_error = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
        // check if name only contains letters and whitespace
        if(!preg_match("/^[a-zA-Z ]*$/", $name)) {
            $name_error = "Only letters and white space allowed";
        }
    }

    if(empty($_POST["email"])) {
        $email_error = "Email is required";
    } else {
        $email = test_input($_POST["email"]);
        // check if e-mail address is well-formed
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $email_error = "Invalid email format";
        }
    }

    if(empty($_POST["phone"])) {
        $phone_error = "Phone is required";
    } else {
        $phone = test_input($_POST["phone"]);
        // check if e-mail address is well-formed
        if(!preg_match("/^[0-9]{1,10}$/", $phone)) {
            //if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)){
            $phone_error = "Invalid phone number";
        }
    }

    if(empty($_POST["message"])) {
        $message_error = "Message Can Not Be Empty";
    } else {
        $message = ($_POST["message"]);
        //$message = test_input($_POST["message"]);
        //$message = "$message";
    }

    //if all the errors are empty, only then send the message
    if($name_error == '' and $email_error == '' and $phone_error == '' and $message_error == '') {
        $message_body = '';
        unset($_POST['submit']);
        foreach($_POST as $key => $value) {
            $message_body .= "$key: $value
";
        }

        require 'PHPMailer/src/Exception.php';
        require 'PHPMailer/src/PHPMailer.php';
        require 'PHPMailer/src/SMTP.php';

        $mail = new PHPMailer(true); // Passing `true` enables exceptions

        try {
            //Server settings
            $mail->SMTPDebug = 0; // Enable verbose debug output
            $mail->isSMTP(); // Set mailer to use SMTP
            $mail->Host = 'mail.ogero.gov.lb'; // Specify main and backup SMTP servers
            //$mail->SMTPAuth = true;                               // Enable SMTP authentication
            //$mail->Username = 'user@example.com';                 // SMTP username
            //$mail->Password = 'secret';                           // SMTP password
            //$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
            $mail->Port = 25; // TCP port to connect to

            //Recipients
            $mail->setFrom('from@example.com', 'Mailer');
            $mail->addAddress('mozes_86@hotmail.com', 'Joe User'); // Add a recipient
            //$mail->addAddress('ellen@example.com');               // Name is optional
            $mail->addReplyTo('info@example.com', 'Information');
            $mail->addCC('cc@example.com');
            $mail->addBCC('bcc@example.com');

            //Attachments
            //$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
            //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

            //Content
            $mail->isHTML(true); // Set email format to HTML
            $mail->Subject = 'Here is the subject';
            $mail->Body = 'This is the HTML message body <b>in bold!</b>';
            $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

            $mail->send();
            //echo 'Message has been sent';
            $success = "Message sent, thank you for contacting us!";
            //reset form values to empty strings
            $name = $email = $phone = $message = '';
        }
        catch(Exception $e) {
            echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
        }
    }
}

function test_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
  • 写回答

2条回答 默认 最新

  • dongyan1993 2018-10-19 17:02
    关注

    You need to use echo to show the value in the textarea.
    Then do not use value=" " , instead use the textarea's value in the between the textarea tags

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 eclipse连接sap后代码跑出来空白
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案