0

0

解决PHP邮件发送后状态信息无法显示的问题

碧海醫心

碧海醫心

发布时间:2025-06-30 18:26:01

|

952人浏览过

|

来源于php中文网

原创

解决php邮件发送后状态信息无法显示的问题

本文旨在解决在使用PHP发送邮件后,状态信息(成功或失败)无法在HTML页面上显示的问题。通过修改文件后缀名、使用$_GET传递状态信息,并进行URL编码和解码,可以有效地在mailSend.php页面上显示邮件发送状态。

问题分析

原始代码存在的问题在于,邮件发送状态信息在 example.php 中生成,但 mailSend.html 页面无法直接访问这些信息,因为 HTML 页面不会执行 PHP 代码。使用 header('Location: mailSend.html') 只是简单地重定向页面,而没有传递任何状态信息。

解决方案

要解决这个问题,需要以下几个步骤:

  1. 将 mailSend.html 重命名为 mailSend.php: 这是因为只有 .php 文件才能被服务器解析并执行 PHP 代码。

    立即学习PHP免费学习笔记(深入)”;

  2. 使用 $_GET 传递状态信息: 在 example.php 中,将状态信息($statusMsg 和 $msgClass)附加到 URL 上,然后进行重定向。

  3. 在 mailSend.php 中获取状态信息: 使用 $_GET 变量获取传递过来的状态信息,并在页面上显示。

具体实现

1. 修改 example.php

将 header('Location: mailSend.html') 替换为以下代码:

$target_url = 'mailSend.php';
$get_data = '?statusMsg=' . urlencode($statusMsg) . '&msgClass=' . urlencode($msgClass);
header('Location: ' . $target_url . $get_data);
exit(); // 确保在重定向后停止执行脚本

代码解释:

PaperFake
PaperFake

AI写论文

下载
  • urlencode() 函数用于对 $statusMsg 和 $msgClass 进行 URL 编码,以确保特殊字符能够正确传递。
  • header('Location: ...') 函数用于重定向页面。
  • exit() 函数用于确保在重定向后停止执行当前脚本,防止出现意外情况。

2. 修改 mailSend.php

在 mailSend.php 文件的顶部,添加以下代码:

<?php
if (isset($_GET['statusMsg']) && isset($_GET['msgClass'])) {
    $statusMsg = urldecode($_GET['statusMsg']);
    $msgClass = urldecode($_GET['msgClass']);
} else {
    $statusMsg = '';
    $msgClass = '';
}
?>

代码解释:

  • isset($_GET['statusMsg']) && isset($_GET['msgClass']) 用于检查 statusMsg 和 msgClass 是否存在于 $_GET 变量中。
  • urldecode() 函数用于对从 URL 传递过来的状态信息进行解码。
  • 如果 statusMsg 和 msgClass 不存在,则将其设置为空字符串,以避免出现未定义变量的错误。

3. 修改 mailSend.php 中的 HTML 代码

确保以下代码存在于 mailSend.php 文件中,用于显示状态信息:

<?php if(!empty($statusMsg)){ ?>
    <p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p>
<?php } ?>

代码解释:

  • 这段代码会检查 $statusMsg 是否为空。如果不为空,则会显示一个带有相应状态信息的段落。
  • !empty($msgClass)?$msgClass:'' 用于根据 $msgClass 的值设置 CSS 类名,以便根据状态类型(成功或失败)应用不同的样式。

完整示例

以下是修改后的 example.php 示例:

<?php
//first we leave this input field blank
$recipient = "";
//if user click the send button
if(isset($_POST['submit'])){
    //access user entered data
    $recipient = $_POST['email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    $sender = "From: <a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" rel="nofollow" target="_blank" >[email protected]</a>";
    //if user leave empty field among one of them
    if(empty($recipient) || empty($subject) || empty($message)){
        $statusMsg = "All inputs are required!";
        $msgClass = 'errordiv';
    }else{

        $uploadStatus = 1;

        // Upload attachment file
        if(!empty($_FILES["attachment"]["name"])){

            // File path config
            $targetDir = "uploads/";
            $fileName = basename($_FILES["attachment"]["name"]);
            $targetFilePath = $targetDir . $fileName;
            $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

            // Allow certain file formats
            $allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
            if(in_array($fileType, $allowTypes)){
                // Upload file to the server
                if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
                    $uploadedFile = $targetFilePath;
                }else{
                    $uploadStatus = 0;
                    $statusMsg = "Sorry, there was an error uploading your file.";
                    $msgClass = 'errordiv';
                }
            }else{
                $uploadStatus = 0;
                $statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
                $msgClass = 'errordiv';
            }
        }

        if($uploadStatus == 1){

            // Recipient
            $toEmail = '<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" rel="nofollow" target="_blank" >[email protected]</a>';

            // Sender
            $from = '<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" rel="nofollow" target="_blank" >[email protected]</a>';
            $fromName = 'example';

            // Subject
            $emailSubject = 'Contact Request Submitted by '.$recipient;

            // Message 
            $htmlContent = '<h2>Contact Request Submitted</h2>
                <p><b>Name:</b> '.$recipient.'</p>
                <p><b>Email:</b> '.$sender.'</p>
                <p><b>Subject:</b> '.$subject.'</p>
                <p><b>Message:</b><br/>'.$message.'</p>';

            // Header for sender info
            $headers = "From: $fromName"." <".$from.">";

            if(!empty($uploadedFile) && file_exists($uploadedFile)){

                // Boundary 
                $semi_rand = md5(time()); 
                $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 

                // Headers for attachment 
                $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 

                // Multipart boundary 
                $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
                "Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n"; 

                // Preparing attachment
                if(is_file($uploadedFile)){
                    $message .= "--{$mime_boundary}\n";
                    $fp =    @fopen($uploadedFile,"rb");
                    $data =  @fread($fp,filesize($uploadedFile));
                    @fclose($fp);
                    $data = chunk_split(base64_encode($data));
                    $message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" . 
                    "Content-Description: ".basename($uploadedFile)."\n" .
                    "Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" . 
                    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
                }

                $message .= "--{$mime_boundary}--";
                $returnpath = "-f" . $recipient;

                // Send email
                $mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);

                // Delete attachment file from the server
                @unlink($uploadedFile);
            }else{
                 // Set content-type header for sending HTML email
                $headers .= "\r\n". "MIME-Version: 1.0";
                $headers .= "\r\n". "Content-type:text/html;charset=UTF-8";

                // Send email
                $mail = mail($toEmail, $emailSubject, $htmlContent, $headers); 
            }

            // If mail sent
            if($mail){
                $statusMsg = 'Your contact request has been submitted successfully !';
                $msgClass = 'succdiv';
            }else{
                $statusMsg = 'Your contact request submission failed, please try again.';
                $msgClass = 'errordiv';
            }
        }    
    }
    $target_url = 'mailSend.php';
    $get_data = '?statusMsg=' . urlencode($statusMsg) . '&msgClass=' . urlencode($msgClass);
    header('Location: ' . $target_url . $get_data);
    exit();
}
?>

以下是修改后的 mailSend.php 示例:

<?php
if (isset($_GET['statusMsg']) && isset($_GET['msgClass'])) {
    $statusMsg = urldecode($_GET['statusMsg']);
    $msgClass = urldecode($_GET['msgClass']);
} else {
    $statusMsg = '';
    $msgClass = '';
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Contact Form</title>
    <style>
        .statusMsg {
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid transparent;
            border-radius: 4px;
        }
        .succdiv {
            color: #3c763d;
            background-color: #dff0d8;
            border-color: #d6e9c6;
        }
        .errordiv {
            color: #a94442;
            background-color: #f2dede;
            border-color: #ebccd1;
        }
    </style>
</head>
<body>

<?php if(!empty($statusMsg)){ ?>
    <p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p>
<?php } ?>

<form action="example.php" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <input style = "padding-left:2%; width: 97%;" type="text" name="name" class="form-control" value="" placeholder="Name" required="">
    </div>
    <div class="form-group">
        <input style = "padding-left:2%; width: 97%;" type="email" name="email" class="form-control" value="" placeholder="Email address" required="">
    </div>
    <div class="form-group">
        <input style = "padding-left:2%; width: 97%;" type="text" name="subject" class="form-control" value="" placeholder="Subject" required="">
    </div>
    <div class="form-group">
        <textarea name="message" class="form-control" placeholder="Write your message here" required="" style = 'border :0.5px solid '></textarea>
    </div>
    <div class="form-group">
        <input type="file" name="attachment" class="form-control" style = 'border :0.5px solid; height: auto;'>
    </div>
    <div class="submit">
        <input type="submit" name="submit" class="btn" value="SUBMIT" style= 'float : right;'>
    </div>
</form>

</body>
</html>

注意事项

  • 确保服务器配置正确,能够解析 PHP 代码。
  • 在实际应用中,应该对用户输入进行验证和过滤,以防止安全漏洞。
  • 可以使用 Session 或 Cookie 来传递状态信息,但这需要更复杂的配置和管理。

总结

通过将 mailSend.html 重命名为 mailSend.php,并使用 $_GET 传递状态信息,可以有效地解决 PHP 邮件发送后状态信息无法显示的问题。这种方法简单易懂,适用于大多数情况。在实际应用中,可以根据具体需求选择更合适的解决方案。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
cookie
cookie

Cookie 是一种在用户计算机上存储小型文本文件的技术,用于在用户与网站进行交互时收集和存储有关用户的信息。当用户访问一个网站时,网站会将一个包含特定信息的 Cookie 文件发送到用户的浏览器,浏览器会将该 Cookie 存储在用户的计算机上。之后,当用户再次访问该网站时,浏览器会向服务器发送 Cookie,服务器可以根据 Cookie 中的信息来识别用户、跟踪用户行为等。

6500

2023.06.30

document.cookie获取不到怎么解决
document.cookie获取不到怎么解决

document.cookie获取不到的解决办法:1、浏览器的隐私设置;2、Same-origin policy;3、HTTPOnly Cookie;4、JavaScript代码错误;5、Cookie不存在或过期等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

368

2023.11.23

阻止所有cookie什么意思
阻止所有cookie什么意思

阻止所有cookie意味着在浏览器中禁止接受和存储网站发送的cookie。阻止所有cookie可能会影响许多网站的使用体验,因为许多网站使用cookie来提供个性化服务、存储用户信息或跟踪用户行为。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

447

2024.02.23

cookie与session的区别
cookie与session的区别

本专题整合了cookie与session的区别和使用方法等相关内容,阅读专题下面的文章了解更详细的内容。

97

2025.08.19

session失效的原因
session失效的原因

session失效的原因有会话超时、会话数量限制、会话完整性检查、服务器重启、浏览器或设备问题等等。详细介绍:1、会话超时:服务器为Session设置了一个默认的超时时间,当用户在一段时间内没有与服务器交互时,Session将自动失效;2、会话数量限制:服务器为每个用户的Session数量设置了一个限制,当用户创建的Session数量超过这个限制时,最新的会覆盖最早的等等。

336

2023.10.17

session失效解决方法
session失效解决方法

session失效通常是由于 session 的生存时间过期或者服务器关闭导致的。其解决办法:1、延长session的生存时间;2、使用持久化存储;3、使用cookie;4、异步更新session;5、使用会话管理中间件。

776

2023.10.18

cookie与session的区别
cookie与session的区别

本专题整合了cookie与session的区别和使用方法等相关内容,阅读专题下面的文章了解更详细的内容。

97

2025.08.19

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

761

2023.08.03

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

26

2026.03.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
10分钟--Midjourney创作自己的漫画
10分钟--Midjourney创作自己的漫画

共1课时 | 0.1万人学习

Midjourney 关键词系列整合
Midjourney 关键词系列整合

共13课时 | 0.9万人学习

AI绘画教程
AI绘画教程

共2课时 | 0.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号