本文旨在解決在使用php發(fā)送郵件后,狀態(tài)信息(成功或失?。o法在html頁面上顯示的問題。通過修改文件后綴名、使用$_GET傳遞狀態(tài)信息,并進(jìn)行URL編碼和解碼,可以有效地在mailSend.php頁面上顯示郵件發(fā)送狀態(tài)。
問題分析
原始代碼存在的問題在于,郵件發(fā)送狀態(tài)信息在 example.php 中生成,但 mailSend.html 頁面無法直接訪問這些信息,因?yàn)?HTML 頁面不會(huì)執(zhí)行 PHP 代碼。使用 header(‘location: mailSend.html’) 只是簡(jiǎn)單地重定向頁面,而沒有傳遞任何狀態(tài)信息。
解決方案
要解決這個(gè)問題,需要以下幾個(gè)步驟:
-
將 mailSend.html 重命名為 mailSend.php: 這是因?yàn)橹挥?.php 文件才能被服務(wù)器解析并執(zhí)行 PHP 代碼。
立即學(xué)習(xí)“PHP免費(fèi)學(xué)習(xí)筆記(深入)”;
-
使用 $_GET 傳遞狀態(tài)信息: 在 example.php 中,將狀態(tài)信息($statusMsg 和 $msgClass)附加到 URL 上,然后進(jìn)行重定向。
-
在 mailSend.php 中獲取狀態(tài)信息: 使用 $_GET 變量獲取傳遞過來的狀態(tài)信息,并在頁面上顯示。
具體實(shí)現(xiàn)
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(); // 確保在重定向后停止執(zhí)行腳本
代碼解釋:
- urlencode() 函數(shù)用于對(duì) $statusMsg 和 $msgClass 進(jìn)行 URL 編碼,以確保特殊字符能夠正確傳遞。
- header(‘Location: …’) 函數(shù)用于重定向頁面。
- exit() 函數(shù)用于確保在重定向后停止執(zhí)行當(dāng)前腳本,防止出現(xiàn)意外情況。
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() 函數(shù)用于對(duì)從 URL 傳遞過來的狀態(tài)信息進(jìn)行解碼。
- 如果 statusMsg 和 msgClass 不存在,則將其設(shè)置為空字符串,以避免出現(xiàn)未定義變量的錯(cuò)誤。
3. 修改 mailSend.php 中的 HTML 代碼
確保以下代碼存在于 mailSend.php 文件中,用于顯示狀態(tài)信息:
<?php if(!empty($statusMsg)){ ?> <p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p> <?php } ?>
代碼解釋:
- 這段代碼會(huì)檢查 $statusMsg 是否為空。如果不為空,則會(huì)顯示一個(gè)帶有相應(yīng)狀態(tài)信息的段落。
- !empty($msgClass)?$msgClass:” 用于根據(jù) $msgClass 的值設(shè)置 css 類名,以便根據(jù)狀態(tài)類型(成功或失?。?yīng)用不同的樣式。
完整示例
以下是修改后的 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 } ?>
注意事項(xiàng)
- 確保服務(wù)器配置正確,能夠解析 PHP 代碼。
- 在實(shí)際應(yīng)用中,應(yīng)該對(duì)用戶輸入進(jìn)行驗(yàn)證和過濾,以防止安全漏洞。
- 可以使用 Session 或 Cookie 來傳遞狀態(tài)信息,但這需要更復(fù)雜的配置和管理。
總結(jié)
通過將 mailSend.html 重命名為 mailSend.php,并使用 $_GET 傳遞狀態(tài)信息,可以有效地解決 PHP 郵件發(fā)送后狀態(tài)信息無法顯示的問題。這種方法簡(jiǎn)單易懂,適用于大多數(shù)情況。在實(shí)際應(yīng)用中,可以根據(jù)具體需求選擇更合適的解決方案。