【问题标题】:Adding File Uploads to PHP Mailer将文件上传添加到 PHP Mailer
【发布时间】:2017-10-16 07:37:11
【问题描述】:

我喜欢我拥有的 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.";
}
?>

非常感谢!

【问题讨论】:

    标签: php forms file-upload


    【解决方案1】:

    您可以使用“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

    希望对你有帮助;)

    【讨论】:

    • 嗨!感谢您的评论!澄清一下,这种方法是让网站的访问者上传要通过联系表提交的文件?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多