将文件上载添加到PHP Mailer

时间:2017-10-16 07:37:12

标签: php forms file-upload

我喜欢我的PHP表单及其工作原理,但无法弄清楚如何添加上传图像文件的功能。我花了几个小时搜索各种资源,尝试添加看似正确的东西,但没有取得任何实际成功。

我意识到这里有很多信息,但我想我无法理解我现在拥有的代码的位置和内容(我使用和编辑PHP的经验)是非常有限的)。这可能非常简单,当它归结为它时,我觉得愚蠢的询问,但最终我还没有能够自己得到它,我希望有人可以指出我正确的方向!

我正在使用的表单:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = strip_tags(trim($_POST["name"]));
    $name = str_replace(array("\r", "\n"), array(" ", " "), $name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $phone = trim($_POST["phone"]);
    $message = trim($_POST["message"]);

    if (empty($name) OR empty($message) OR ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo "There was a problem with your submission. Please complete the form and try again.";
        exit;
    }
    $recipient = "myemail@gmail.com";

    $subject = "New message from $name";

    $email_content = "Name: $name\n";
    $email_content .= "Phone: $phone\n\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    $email_headers = "From: $name <$email>";

    if (mail($recipient, $subject, $email_content, $email_headers)) {
        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        http_response_code(500);
        echo "Something went wrong and we couldn't send your message.";
    }
} else {
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}
?>

非常感谢!

1 个答案:

答案 0 :(得分:0)

您可以使用“addAttachment”方法(如果提供文件路径)或“addStringAttachment”方法(如果提供文件内容),使用PHPmailer库向发送的电子邮件添加附件: https://github.com/PHPMailer/PHPMailer/wiki/Tutorial

如果您在HTML文件上传字段中上传服务器上的文件时遇到问题,请务必在标记中添加以下属性:

enctype="multipart/form-data"

在PHP部分中,您将在$ _FILE中找到文件的名称/路径,只需将其移动到您想要的服务器上。您可以在此页面上找到一些示例:https://www.w3schools.com/php/php_file_upload.asp

希望它有所帮助;)