You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加附件选项后联系表单无法发送,求附件字段验证方案

Hey there! Let's figure out why your contact form stopped sending emails after adding attachments. I spotted a few key issues in your PHP code that are causing this problem, along with clear fixes to get it working again:


1. Broken Attachment Validation Check

Your current check if (empty($_FILES["attachment"])) will always return false—even when no files are selected—because $_FILES["attachment"] is an array structure that exists regardless of uploads. Instead, we need to validate if any uploaded file is actually valid:

Replace your existing attachment validation code with this:

$attachment_error = "";
$has_valid_attachment = false;

// Check if any uploaded file is valid
if (isset($_FILES['attachment']['name'])) {
    foreach ($_FILES['attachment']['name'] as $index => $filename) {
        // Verify file was uploaded without errors and has a name
        if (!empty($filename) && $_FILES['attachment']['error'][$index] === UPLOAD_ERR_OK) {
            $has_valid_attachment = true;
            break;
        }
    }
}

// Uncomment below if you require at least one attachment
// if (!$has_valid_attachment) {
//     $attachment_error = "Palun sisesta enda eluloo fail";
// }

2. Undefined Message Variable When No Attachments Exist

Right now, if no attachments are uploaded, $datamsg is never initialized. This causes the mail() function to fail because it's trying to send an undefined value. We'll fix this by setting a base message structure that works with or without attachments.

3. Inconsistent MIME Header & Attachment Handling

Your code overwrites headers only when attachments exist, leading to broken email formatting. Here's the corrected full mail-handling block (replace your existing mail logic with this):

if ($name_error == '' && $email_error == '' && $message_error == '' && ($attachment_error == '' || $has_valid_attachment)) {
    $to = 'myemail@gmail.com';
    $subject = 'Eesti Elulood';
    $plain_message = "Sulle saadeti kiri Rannu koguduse kodulehelt.\n\nSaatja nimi: $thename\n\nSaatja email: $email\n\nSõnum: $message";

    // Setup MIME boundary for multi-part emails
    $semi_rand = md5(uniqid(time()));
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

    // Base headers (works with or without attachments)
    $headers = "From: " . '=?UTF-8?B?' . base64_encode($thename) . '?=' . " <$email>" . PHP_EOL;
    $headers .= "Reply-To: " . '=?UTF-8?B?' . base64_encode($thename) . '?=' . " <$email>" . PHP_EOL;
    $headers .= "Return-Path: $email" . PHP_EOL;
    $headers .= "MIME-Version: 1.0" . PHP_EOL;
    $headers .= "Content-Type: multipart/mixed;" . PHP_EOL;
    $headers .= " Boundary=\"{$mime_boundary}\"";

    // Initialize message content
    $datamsg = "This is a multi-part message in MIME format." . PHP_EOL . PHP_EOL;
    $datamsg .= "--{$mime_boundary}" . PHP_EOL;
    $datamsg .= "Content-Type: text/plain; Charset=\"UTF-8\"" . PHP_EOL;
    $datamsg .= "Content-Transfer-Encoding: 8bit" . PHP_EOL . PHP_EOL;
    $datamsg .= $plain_message . PHP_EOL . PHP_EOL;

    // Process valid attachments
    if (isset($_FILES['attachment']['name'])) {
        for ($index = 0; $index < count($_FILES['attachment']['name']); $index++) {
            $filename = $_FILES['attachment']['name'][$index];
            $tmp_path = $_FILES['attachment']['tmp_name'][$index];
            $upload_error = $_FILES['attachment']['error'][$index];

            // Only process files that uploaded successfully
            if (!empty($filename) && $upload_error === UPLOAD_ERR_OK && is_readable($tmp_path)) {
                $file_content = file_get_contents($tmp_path);
                if ($file_content !== false) {
                    $data_file = chunk_split(base64_encode($file_content));
                    $datamsg .= "--{$mime_boundary}" . PHP_EOL;
                    $datamsg .= "Content-Type: application/octet-stream; Name=\"{$filename}\"" . PHP_EOL;
                    $datamsg .= "Content-Disposition: attachment; Filename=\"{$filename}\"" . PHP_EOL;
                    $datamsg .= "Content-Transfer-Encoding: base64" . PHP_EOL . PHP_EOL . $data_file . PHP_EOL . PHP_EOL;
                }
            }
        }
    }

    // Close the MIME boundary
    $datamsg .= "--{$mime_boundary}--";

    // Remove the @ to see debugging errors (restore it later)
    if (mail($to, '=?UTF-8?B?' . base64_encode($subject) . '?=', $datamsg, $headers, "-f$email")) {
        $success = "Täname! Sõnum saadeti edukalt.";
    } else {
        $error = "Vabandust, kuid sõnumit ei saanud saata. Palun proovige uuesti!";
        // Uncomment below to log errors for debugging
        // error_log("Mail failed: " . print_r(error_get_last(), true));
    }
}

4. Fix the Form Redirect Issue

When you submit the form, it jumps to index.php because $_SERVER['PHP_SELF'] points to your main file. To keep users on the form page and show success/error messages, add this redirect logic right after setting $success or $error:

// Store messages in session and redirect back to the form
session_start();
$_SESSION['success'] = $success;
$_SESSION['error'] = $error;
$_SESSION['thename'] = $thename;
$_SESSION['email'] = $email;
header("Location: " . $_SERVER['HTTP_REFERER']);
exit;

Then update your form HTML to pull these values from the session:

<?php
session_start();
$success = isset($_SESSION['success']) ? $_SESSION['success'] : '';
$error = isset($_SESSION['error']) ? $_SESSION['error'] : '';
$thename = isset($_SESSION['thename']) ? $_SESSION['thename'] : '';
$email = isset($_SESSION['email']) ? $_SESSION['email'] : '';

// Clear session after displaying messages
unset($_SESSION['success'], $_SESSION['error'], $_SESSION['thename'], $_SESSION['email']);
?>

Quick Debugging Tips

  • Remove the @ before mail() temporarily to see PHP errors related to mail sending
  • Check your server's mail logs (typically /var/log/mail.log on Linux) for delivery issues
  • Ensure your server allows file uploads and adjust upload_max_filesize/post_max_size in php.ini if you need to accept larger files

内容的提问来源于stack exchange,提问作者Ilona

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:48:51