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

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

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

问题分析

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

解决方案

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

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

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

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

在 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(); // 确保在重定向后停止执行脚本

代码解释:

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

2. 修改 mailSend.php

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


代码解释:

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

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

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

    <p class="statusMsg ">

代码解释:

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

完整示例

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

<?php//first we leave this input field blank$recipient = "";//if user click the send buttonif(isset($_POST['submit'])){    //access user entered data    $recipient = $_POST['email'];    $subject = $_POST['subject'];    $message = $_POST['message'];    $sender = "From: [email protected]";    //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 = '[email protected]';            // Sender            $from = '[email protected]';            $fromName = 'example';            // Subject            $emailSubject = 'Contact Request Submitted by '.$recipient;            // Message             $htmlContent = '

Contact Request Submitted

Name: '.$recipient.'

Email: '.$sender.'

Subject: '.$subject.'

Message:
'.$message.'

'; // Header for sender info $headers = "From: $fromName"." "; 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.0n" . "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: 7bitnn" . $htmlContent . "nn"; // 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: base64nn" . $data . "nn"; } $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 .= "rn". "MIME-Version: 1.0"; $headers .= "rn". "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 示例:

    Contact Form            .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;        }        <p class="statusMsg ">

注意事项

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

总结

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

以上就是解决PHP邮件发送后状态信息无法显示的问题的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1261107.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
通过 PHP 在 HTML 页面中执行 Shell 脚本
上一篇 2025年12月10日 06:45:46
PHP怎么实现文件批量解密 文件批量解密功能实现教程
下一篇 2025年12月10日 06:48:46

相关推荐

发表回复

登录后才能评论
关注微信