2026-07-15

Simple PHP form: Attachment to email (code golf)

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

Simple PHP form: Attachment to email (code golf)

Simple PHP Form: Attachment to Email (Code Golf)

Imagine you are building a simple utility where a website visitor can upload a file—perhaps an image or a document—along with a short message, and have that entire package immediately delivered via email. The requirement is simplicity: minimal code, minimal setup, ideally contained in a single script. This scenario perfectly scratches the itch for "code golf" while demanding robust handling of server-side data and file streams.

The simplest way to accomplish this involves leveraging PHP's built-in superglobals ($_FILES) and standard mail functions. While frameworks like Laravel abstract much of this complexity into service classes, understanding the raw mechanics is crucial, especially when optimizing for minimal footprint or building custom solutions.

The Core Challenge: File Handling in PHP

Handling file uploads securely requires careful attention to path traversal, file permissions, and ensuring the content is correctly formatted as an attachment rather than just a corrupted stream. The complexity often lies not in sending the email itself, but in correctly packaging the binary file data into the MIME structure that the mail server expects.

For a code-golf solution, we aim for directness. We need to read the uploaded file temporarily, grab its contents, and prepend those contents to the email body headers.

The Simplest Implementation

The most straightforward approach involves processing the upload, reading the file content into memory or a temporary stream, and then using PHP's mail() function, carefully constructing the MIME boundaries for attachments.

Here is a demonstration focusing on simplicity and self-containment:

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $uploadDir = 'uploads/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $fileTmpName = $_FILES['file']['tmp_name'];
    $fileName = basename($_FILES['file']['name']);
    $targetPath = $uploadDir . $fileName;

    // 1. Move the uploaded file to a safe location (Crucial security step)
    if (move_uploaded_file($fileTmpName, $targetPath)) {
        
        // 2. Prepare the email content
        $to = 'recipient@example.com';
        $subject = 'File Uploaded: ' . $fileName;
        $message = "Please find the attached file with this message.";

        // 3. Construct the MIME message for attachment
        $headers = "From: webmaster@example.com\r\n";
        $headers .= "Reply-To: webmaster@example.com\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary=\"--boundary-\"\r\n";

        // Start the attachment part
        $headers .= "--boundary-\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
        $headers .= "\r\n"; // Blank line separates headers from body
        $headers .= $message . "\r\n";

        // Start the actual file attachment content
        $fileContent = file_get_contents($targetPath);
        $headers .= "--boundary-\r\n";
        $headers .= "Content-Type: application/octet-stream; name=\"{$fileName}\"\r\n";
        $headers .= "Content-Disposition: attachment; filename=\"{$fileName}\"\r\n\r\n";
        $headers .= $fileContent;

        // 4. Send the email
        if (mail($to, $subject, $headers)) {
            echo "File successfully uploaded and emailed.";
        } else {
            echo "Error sending email.";
        }
    } else {
        echo "Error: File could not be moved.";
    }
}

?>

Security and Best Practices

While the code above achieves the goal of simplicity, a senior developer must emphasize security. Notice the critical step where we use move_uploaded_file() to place the file in a dedicated, controlled directory (uploads/). Never trust user input for file paths. Always sanitize filenames and ensure the destination directory has strict permissions (which is why setting permissions like 0777 during creation should be avoided in production; use stricter settings).

The use of mail() directly can sometimes be unreliable depending on server configuration. For mission-critical applications, moving towards using dedicated libraries or services that handle complex MIME encoding more reliably is often preferred. For instance, when building larger systems, understanding the underlying principles of data transport, much like how robust systems are designed in environments like those promoted by Laravel, becomes essential.

Conclusion

Achieving a simple file-to-email attachment involves mastering the interaction between PHP's file handling functions and email formatting standards (MIME). By focusing on reading the temporary file contents and manually constructing the multipart message boundaries, we can achieve a concise solution that meets the code-golf requirement while maintaining functional integrity. Remember that simplicity in code doesn't mean sacrificing security or reliability; it means choosing the most direct path to a secure outcome.

Note: Blog content is currently available in English.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.