带附件的Contact Form无附件提交报错问题求助
问题:无附件提交联系表单时出现错误并页面空白
我开发了一个带文件附件功能的联系表单,填写完整表单并附加文件时可正常运行;但不附加文件提交时,页面变成空白(表单不可见),同时提示:Sorry, there was an error uploading your file.。我推测问题出在缺少必要的条件判断,相关代码如下:
<?php // debug error_reporting(E_ALL); // Ez a report all errors ini_set("display_errors", 1); if(isset($_POST['submit'])){ // Get the submitted form data $name = trim($_POST['name']); $email = trim($_POST['email']); $dropdown = trim($_POST['dropdown']); $message = trim($_POST['message']); //validation for email $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if (!preg_match($email_exp, $email)) { echo "<p style='color:red;'>A megadott E-mail cím érvénytelen.</p>"; exit; } // Upload attachment file if(!empty($_FILES["attachment"]["name"])){ foreach ($_FILES["attachment"]["name"] as $key => $val) { $fileerror = $_FILES['attachment']['error'][$key]; // get the error (if any) //validate form field for attaching the file if($fileerror > 0) { echo "<p style='color:red;'>Feltöltési hiba vagy Nincs fájl feltöltve.</p>"; exit; } // Attachment path config $targetDir = "uploads/"; $fileName = basename($_FILES['attachment']['name'][$key]); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); // Allow certain attachment formats $allowTypes = array('jpg', 'png', 'jpeg'); if(in_array($fileType, $allowTypes)){ // Check the attachment size if ($_FILES['attachment']['size'][$key] > 6000000) { echo "<p style='color:red;'>A csatolt kép nem haladhatja meg a 6MB-ot</p>"; exit; }else{ // Upload attachment to the server if(move_uploaded_file($_FILES['attachment']['tmp_name'][$key], $targetFilePath)){ $uploadedFile = $targetFilePath; }else{ echo "<p style='color:red;'>Sorry, there was an error uploading your file.</p>"; exit; } } }else{ echo "<p style='color:red;'>Sorry, only JPG, JPEG, & PNG files are allowed to upload.</p>"; exit; } } } } if(isset($_POST['submit'])){ //If everything above is ok then move further //Use PHPmailer require "phpmailer/PHPMailerAutoload.php"; $mail = new PHPMailer; $mail->CharSet = "UTF-8"; $mail->Encoding = "16bit"; //Mailbody to send in an email $mailbody =''; //Sender email address $sender = ""; // Gmail SMTP username $mail->isSMTP(); // Set mailer to use SMTP $mail->SMTPDebug = 0; //See errors, change it to 4 $mail->Host = ''; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $sender; // SMTP username $mail->Password = '';// Gmail SMTP password $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `SSL` also accepted $mail->Port = 465; // TCP port to connect to $mail->setFrom($sender, $name); $mail->addAddress('pixelkontakthu@gmail.com', 'PixelKontakt'); // Add a recipient //$mail->addAddress('name@example.com'); //add more recipient (optional) $mail->addReplyTo($email, $name); //$mail->addCC('cc@example.com'); //$mail->addBCC('bcc@example.com'); //Add attachment if(is_array($_FILES)) { foreach ($_FILES["attachment"]["name"] as $key => $val) { $fileName = basename($_FILES['attachment']['name'][$key]); $targetFilePath = $targetDir . $fileName; $uploadedFile = $targetFilePath; $mail->AddAttachment($uploadedFile, $_FILES["attachment"]["name"][$key], 'base64', 'mime/type'); } } $mail->isHTML(true); // Set email format to HTML $mail->Encoding = 'base64'; $mail->Subject = $dropdown.'-ra jelentkezett '.$name; $mail->Body = $mailbody; //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; //Email your contact form data with an attachment using Gmail SMTP with PHPMailer if(!$mail->send()){ echo "<p style='color:red;'>Message could not be sent. Please try again.</p>"; echo 'Mailer Error: ' . $mail->ErrorInfo; }else{ echo "<p style='color:green;'>Üzenet sikeresen elküldve!</p>"; //To delete all sent files from the uploaded folder; foreach ($_FILES["attachment"]["name"] as $key => $val) { $fileName = basename($_FILES['attachment']['name'][$key]); $targetFilePath = $targetDir . $fileName; $uploadedFile = $targetFilePath; @unlink($uploadedFile); } } } ?>
我排查了以下代码段,但没找到解决办法:
// Upload attachment file if(!empty($_FILES["attachment"]["name"])){ foreach ($_FILES["attachment"]["name"] as $key => $val) {
问题根源与修复方案
1. 文件错误码判断逻辑错误
无附件时,$_FILES['attachment']['error']会返回UPLOAD_ERR_NO_FILE(错误码4),属于正常情况,但原代码直接判断$fileerror > 0就终止程序,导致误判。修改错误判断逻辑:
// 替换原错误判断 if($fileerror > 0 && $fileerror != 4) { echo "<p style='color:red;'>Feltöltési hiba vagy Nincs fájl feltöltve.</p>"; exit; } // 跳过无文件的项 if($fileerror == 4) continue;
2. 变量作用域问题
$targetDir仅在有附件时定义,无附件时第二个判断块调用该变量会触发未定义错误。将$targetDir移到第一个判断块顶部全局定义:
// 在获取表单数据后添加 $targetDir = "uploads/";
3. 无附件时的循环处理
原代码在添加附件时直接遍历$_FILES["attachment"]["name"],无附件时该数组不存在会触发警告。修改为仅当有附件时执行循环:
// 替换原添加附件代码 if(!empty($_FILES["attachment"]["name"])) { foreach ($_FILES["attachment"]["name"] as $key => $val) { $fileName = basename($_FILES['attachment']['name'][$key]); $targetFilePath = $targetDir . $fileName; $mail->AddAttachment($targetFilePath, $_FILES["attachment"]["name"][$key]); } }
4. 合并重复的提交判断
两个独立的isset($_POST['submit'])块易导致逻辑混乱,将邮件发送代码合并到第一个判断块内,避免变量作用域问题。
修复后的完整代码
<?php // debug error_reporting(E_ALL); ini_set("display_errors", 1); if(isset($_POST['submit'])){ // Get the submitted form data $name = trim($_POST['name']); $email = trim($_POST['email']); $dropdown = trim($_POST['dropdown']); $message = trim($_POST['message']); $targetDir = "uploads/"; // 全局定义路径 //validation for email $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if (!preg_match($email_exp, $email)) { echo "<p style='color:red;'>A megadott E-mail cím érvénytelen.</p>"; exit; } // Upload attachment file $uploadedFiles = []; if(!empty($_FILES["attachment"]["name"])){ foreach ($_FILES["attachment"]["name"] as $key => $val) { $fileerror = $_FILES['attachment']['error'][$key]; // 排除无文件的正常情况(错误码4) if($fileerror > 0 && $fileerror != 4) { echo "<p style='color:red;'>Feltöltési hiba vagy Nincs fájl feltöltve.</p>"; exit; } // 跳过无文件的项 if($fileerror == 4) continue; $fileName = basename($_FILES['attachment']['name'][$key]); $targetFilePath = $targetDir . $fileName; $fileType = strtolower(pathinfo($targetFilePath,PATHINFO_EXTENSION)); // Allow certain attachment formats $allowTypes = array('jpg', 'png', 'jpeg'); if(!in_array($fileType, $allowTypes)){ echo "<p style='color:red;'>Sorry, only JPG, JPEG, & PNG files are allowed to upload.</p>"; exit; } // Check the attachment size if ($_FILES['attachment']['size'][$key] > 6000000) { echo "<p style='color:red;'>A csatolt kép nem haladhatja meg a 6MB-ot</p>"; exit; } // Upload attachment to the server if(move_uploaded_file($_FILES['attachment']['tmp_name'][$key], $targetFilePath)){ $uploadedFiles[] = $targetFilePath; }else{ echo "<p style='color:red;'>Sorry, there was an error uploading your file.</p>"; exit; } } } // Use PHPmailer require "phpmailer/PHPMailerAutoload.php"; $mail = new PHPMailer; $mail->CharSet = "UTF-8"; $mail->Encoding = "16bit"; // Mailbody to send in an email $mailbody = "Név: $name<br>E-mail: $email<br>Kategória: $dropdown<br>Üzenet: $message"; // 补充邮件内容 // Sender email address $sender = ""; // Gmail SMTP username $mail->isSMTP(); $mail->SMTPDebug = 0; $mail->Host = ''; // Specify main and backup SMTP servers $mail->SMTPAuth = true; $mail->Username = $sender; $mail->Password = '';// Gmail SMTP password $mail->SMTPSecure = 'ssl'; $mail->Port = 465; $mail->setFrom($sender, $name); $mail->addAddress('pixelkontakthu@gmail.com', 'PixelKontakt'); $mail->addReplyTo($email, $name); // Add attachment foreach($uploadedFiles as $filePath){ $mail->AddAttachment($filePath, basename($filePath)); } $mail->isHTML(true); $mail->Encoding = 'base64'; $mail->Subject = $dropdown.'-ra jelentkezett '.$name; $mail->Body = $mailbody; // Send email if(!$mail->send()){ echo "<p style='color:red;'>Message could not be sent. Please try again.</p>"; echo 'Mailer Error: ' . $mail->ErrorInfo; }else{ echo "<p style='color:green;'>Üzenet sikeresen elküldve!</p>"; // Delete uploaded files foreach($uploadedFiles as $filePath){ @unlink($filePath); } } } ?>
内容的提问来源于stack exchange,提问作者PixelKontakt
相关产品推荐
相关产品推荐

