如何用PHP建立一个联系表格

137 阅读5分钟

用PHP建立一个联系表

PHP是一种用于创建交互式网络应用程序的编程语言。它是一种流行的服务器端语言。

在本教程中,将使用PHP建立一个联系表单。它将包括表单验证、使用Gmail SMTP服务器发送邮件的能力以及[PHPMailer库]等功能。

我们最终的联系表单将如下图所示。

Project

前提条件

要学习本教程,读者应该。

  • 对HTML和PHP有基本了解。
  • 安装了PHP和XAMMP。我们将使用 XAMMP 在我们的机器上本地运行 PHP。

下载并安装XAMMP。

项目设置和概述

在这一部分,我们将设置我们的项目。注意,本教程使用XAMPP(一个免费的跨平台的PHP开发环境)。

因此在安装后,启动ApacheMySQL 模块。

XAMPP Settings

接下来,打开你的浏览器并导航到http://localhost/dashboard/。你应该看到以下内容。

XAMPP Server Hompage

PHP新项目

让我们来创建一个新的PHP项目。

第1步

在你的C: drive ,打开文件夹xampp 。在这个文件夹中,导航到htdocs 目录,并创建一个新的文件夹,名称为php-contact

第2步

在你最喜欢的代码编辑器中打开php-contact 文件夹,并创建一个名为index.php 的新文件。

将下面的代码粘贴在index.php 文件中。

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Document</title>
  </head>
  <body>
    <h1>Hello World</h1>
  </body>
</html>

导航到http://localhost/php-contact/ ,你应该看到一个标题,上面写着Hello World

注意,我们没有给index.php ,因为在PHP中,默认情况下,导航到一个文件夹的根页面会自动加载index.php文件。

创建表单

在本节中,我们将在index.php 内创建一个基本的表单。

用下面的代码替换之前的代码。

<!DOCTYPE html>
<html>

<head>
    <!--Import Google Icon Font-->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!--Import materialize.css-->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">


    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
        .error {
            color: white;
            background-color: crimson;
            border-radius: 7px;
            text-align: center;
        }

        .success {
            background-color: darkgreen;
            color: white;
            border-radius: 7px;
            text-align: center;
        }
    </style>
</head>

<body>

    <main class="container">
        <h4>Contact</h4>

        <hr>

        <div class="row">
            <div class="col s12 l5">
                <span class="bold">Get in touch with me via email</span>
            </div>
            <div class="col s12 l5 offset-l2">

                <div class="success"><?php echo $success ?></div>
                <div class="error"><?php echo $error ?></div>
                <form action="index.php" method="post">

                    <div class="input-field">
                        <i class="material-icons prefix">account_circle</i>
                        <input type="text" name="name" id="name" value="<?php echo htmlspecialchars($name) ?>">

                        <label for="name">Your name*</label>
                        <div class="error"><?php echo $errors["name"] ?></div>
                    </div>
                    <div class="input-field">
                        <i class="material-icons prefix">email</i>
                        <input type="email" name="email" id="email" value="<?php echo htmlspecialchars($email) ?>">
                        <label for="email">Your email*</label>
                        <div class="error"><?php echo $errors["email"] ?></div>
                    </div>
                    <div class="input-field">
                        <i class="material-icons prefix">mode_edit</i>
                        <textarea id="message" class="materialize-textarea" name="message"><?php echo htmlspecialchars($message) ?></textarea>
                        <label for="message">Your Message*</label>
                        <div class="error"><?php echo $errors["message"] ?></div>
                    </div>
                    <div class="input-field center">
                        <input type="submit" class="btn-large z-depth-0" name="submit" id="submit" value="Send"></input>
                    </div>

                </form>
            </div>
        </div>
    </main>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

</body>
</html>

这里发生了什么

  1. 我们用POST方法创建了一个基本的表单,最终将请求送回这个页面。

  2. 我们还使用materializeCSS做了一些默认的样式设计。

  3. 我们在HTML页面中添加了一些PHP变量,以呼出错误信息或在表单中输入的值。请注意,我们还没有在我们的PHP脚本中创建这些变量,所以如果你刷新你的浏览器,它会产生一些错误。

htmlspecialchars函数用于将特殊字符变为HTML能够理解并正确显示的字符。这可以防止像跨站脚本攻击(XSS)这样的漏洞,因为它将所有有害的字符替换成无害的HTML实体。因此,在你的HTML中输出用户的输入时,一定要包括这个函数。

PHP中的表单验证

在本节中,我们将在index.php 中创建网页的逻辑,以验证用户的输入。

在文件的顶部添加下面的代码。

<?php

$success = "";
$error = "";
$name = $message = $email = "";
$errors = array('name' => '', 'email' => '', 'message' => '');

?>

你应该知道的是

在上面的代码中。

  1. 我们创建了几个变量来存储user input,errorsuccess 信息。
  2. 我们还创建了一个errors 数组来存储特定的错误信息。

导航回到homepage ,刷新你的浏览器。

注意这个PHP脚本被包裹在一个<?php ?> 标签内,如果不是这样,它就不会被当作PHP代码。

接下来,在PHP标签内添加以下函数。

function SanitizeString($var)
{
    $var = strip_tags($var);
    $var = htmlentities($var);
    return stripslashes($var);
}

你应该知道的是

  1. 这个函数用于通过删除HTML entitiesslashestags ,对字符串(用户输入)进行消毒。这对于防止黑客输入恶意文本是非常重要的。

接下来,添加以下代码。

if (isset($_POST["submit"])) {
    if (empty(trim($_POST["name"]))) {
        $errors['name'] = "Your name is required";
    } else {
        $name = SanitizeString($_POST["name"]);
        if (!preg_match('/^[a-zA-Z\s]{6,50}$/', $name)) {
            $errors['name'] = "Only letters and spaces allowed";
        }
    }

    if (empty(trim($_POST["email"]))) {
        $errors["email"] = "Your email is required";
    } else {
        $email = SanitizeString($_POST["email"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors["email"] = "Pls give a proper email address";
        }
    }

    if (empty(trim($_POST["message"]))) {
        $errors["message"] = "Please type your message";
    } else {
        $message = SanitizeString($_POST["message"]);
        if (!preg_match("/^[a-zA-Z\d\s]+$/", $message)) {
            $errors["message"] = "Only letters, spaces and maybe numbers allowed";
        }
    }

    if (array_filter($errors)) {
    } else {
        // Send email
    }
}

这里发生了什么

  1. 上面的条件语句检查表单是否被提交。如果提交了,它将执行几个功能来净化和验证用户的输入或显示任何错误信息。

  2. trimempty 函数的组合检查表单是否为空。

  3. preg_match 函数用于检查基于一些标准的用户输入,使用regex

  4. 最后,如果在errors 数组中没有错误,邮件将被发送。

用PHP Mailer和Google Gmail SMTP服务器发送邮件

要用Gmail发送邮件,我们需要有一个Google账户。

下载PHP mailer

PHPMailer是一个用PHP编写的用于发送电子邮件的流行库。

php-contact目录下解压该包。

你可以通过readme文件来了解这个库的更多信息。

配置你的Gmail账户

Google Less Secure Homepage

请注意,开启了2步验证的谷歌账户不能用于安全应用程序。

相反,你使用应用程序密码。

index.php 文件的顶部添加以下代码。


// Include packages and files for PHPMailer and SMTP protocol
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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

// Initialize PHP mailer, configure to use SMTP protocol and add credentials

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Mailer = "smtp";

$mail->SMTPDebug  = 1;
$mail->SMTPAuth   = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port       = 587;
$mail->Host       = "smtp.gmail.com";
$mail->Username   = "<paste your gmail account here>";
$mail->Password   = "<paste Google password or app password here>";

你应该知道的是

在上面的代码中。

  1. 我们包含了PHPMailer和SMTP协议的包和文件。
  2. 我们初始化了PHP Mailer,将其配置为使用SMTP协议,并添加了凭证。

接下来,用下面的代码替换这个注释// Send email

try {

    $mail->setFrom('<paste your gmail account here>', '<paste your name here>');

    $mail->addAddress($email, $name);

    $mail->Subject = 'Build a contact form with PHP';

    $mail->Body = $message;

    // send mail

    $mail->send();

    // empty users input

    $name = $message = $email = "";

    $success = "Message sent successfully";

} catch (Exception $e) {

    // echo $e->errorMessage(); use for testing & debugging purposes
    $error = "Sorry message could not send, try again";
} catch (Exception $e) {

    // echo $e->getMessage(); use for testing & debugging purposes
    $error = "Sorry message could not send, try again";
}

这里发生了什么

  1. 我们添加了电子邮件的发件人和名字(setFrom函数)
  2. 我们还添加了电子邮件的收件人(addAddress函数)
  3. 我们添加了主题和正文,最后发送了邮件。

总结

在本教程中,我们已经学会了如何在PHP网站上添加一个联系表单。我们还研究了如何使用Google Gmail帐户和PHPMailer库来发送邮件。