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

代码解释:

  • 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.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 示例:

<?php if (isset($_GET['statusMsg']) && isset($_GET['msgClass'])) {     $statusMsg = urldecode($_GET['statusMsg']);     $msgClass = urldecode($_GET['msgClass']); } else {     $statusMsg = '';     $msgClass = ''; } ?>        Contact Form         <?php if(!empty($statusMsg)){ ?>     <p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p> <?php } ?>  

注意事项

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

总结

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

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享