Simple PHP form: Attachment to email (code golf)
Building a file upload mechanism that bypasses permanent storage is a common requirement for lightweight tools or temporary data collection. The goal here is specific: allow a user to select a file and type a message, then immediately attach that file to an outgoing email without it persisting on the server. This approach minimizes disk I/O and security surface area by avoiding the need for a dedicated uploads directory or long-term retention logic.
The core challenge lies in bridging the gap between $_FILES and mail() within a single script execution. Standard PHP practices often involve moving files from the temporary upload directory ($_FILES['file']['tmp_name']) to a specific folder before sending the email. However, for this use case, we must skip that persistence step entirely. We need to stream the file directly into the MIME multipart body of the email message.
The simplest implementation relies on PHP's built-in mail() function combined with raw string manipulation or the php://temp wrapper to construct a valid MIME multipart message. The script needs to handle two distinct states: displaying the form when no data is posted, and processing the submission when PHP_POST_FILES indicates an upload occurred.
Here is how the logic flows in a self-contained file. First, we check if the request method is POST. If not, we render the HTML form. The form must use enctype="multipart/form-data" to handle binary data correctly. We should also include a text area for the message body and an input for the recipient's email address, as PHP's mail() function requires at least one recipient in the "To" field.
<?php
// Configuration
$recipient = isset($_POST['to']) ? $_POST['to'] : 'admin@example.com';
$message = isset($_POST['message']) ? htmlspecialchars($_POST['message']) : '';
$file = $_FILES['file'] ?? null;
// State: Display Form or Process Upload?
if (!$file || !isset($file['tmp_name'])) {
// Render the form
?>
<!DOCTYPE html>
<html>
<head><title>File Email</title></head>
<body>
<form method="post" enctype="multipart/form-data">
<label>To: <input type="email" name="to" value="<?php echo htmlspecialchars($recipient); ?>" required></label><br>
<textarea name="message" rows="4" cols="50"><?php echo $message; ?></textarea><br>
<input type="file" name="file" required><br>
<button type="submit">Send Email</button>
</form>
</body>
</html>
<?php
} else {
// Process the upload and send email
$filename = basename($file['name']);
$content_type = mime_content_type($file['tmp_name']);
// Construct the MIME multipart message manually to avoid file storage
$boundary = '====' . bin2hex(random_bytes(16)) . '====';
$body = "";
// Add text part
$body .= "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=UTF-8\r\n";
$body .= "\r\n$message\r\n";
// Add attachment part
$body .= "--$boundary\r\n";
$body .= "Content-Type: $content_type; name=\"$filename\"\r\n";
$body .= "Content-Disposition: attachment; filename=\"$filename\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "\r\n";
// Stream the file directly to base64 without saving it
$handle = fopen($file['tmp_name'], 'rb');
while (!feof($handle)) {
$chunk = fread($handle, 8192);
$body .= chunk_split(base64_encode($chunk));
}
fclose($handle);
$body .= "--$boundary--\r\n";
// Send the email
$headers = "From: noreply@example.com\r\n";
$headers .= "Reply-To: $recipient\r\n";
$headers .= "X-Priority: 3\r\n";
mail($recipient, 'File Attachment', $body, $headers);
if ($file['error'] == UPLOAD_ERR_OK) {
echo "Email sent successfully. The file was streamed directly to the mail queue.";
} else {
echo "Upload error: {$file['error']}.";
}
}
This implementation prioritizes size and simplicity by avoiding external libraries like PHPMailer or SwiftMailer. While those libraries offer robustness for production environments handling thousands of emails, this approach fits the "code golf" criteria by keeping dependencies to zero. The trade-off is that you must carefully manage the MIME boundaries and headers manually. Errors in the Content-Type or missing newlines will cause mail clients to fail parsing the attachment.
Security considerations remain critical even in a minimal script. We use htmlspecialchars() on form inputs to prevent XSS if the email body is viewed in a web interface, though for direct email transmission, this is less about the mailer and more about the form display. The filename is sanitized using basename() to prevent directory traversal issues, ensuring only the intended file name appears in the email header.
A potential pitfall here is the size of the email. Base64 encoding increases the payload size by roughly 33%. If the original file exceeds typical email client limits (often around 25MBâ30MB depending on the provider), the message will bounce. Additionally, some strict mail servers may flag emails with inline base64 attachments generated via mail() as spam if headers are malformed. Always test the output by sending a message to an external address and verifying the attachment renders correctly in the recipient's client.