What are some best practices for sending emails with attachments using PHP forms?
When sending emails with attachments using PHP forms, it is important to ensure that the file is properly uploaded and attached to the email. One best practice is to use PHP's built-in functions like `move_uploaded_file()` to handle file uploads securely. Additionally, make sure to set the appropriate headers in the email to indicate that it contains an attachment.
<?php
// Check if file is uploaded successfully
if(isset($_FILES['attachment']) && $_FILES['attachment']['error'] == UPLOAD_ERR_OK) {
$file_name = $_FILES['attachment']['name'];
$file_tmp = $_FILES['attachment']['tmp_name'];
// Move the uploaded file to a desired location
move_uploaded_file($file_tmp, 'uploads/' . $file_name);
// Set email headers
$headers = "From: sender@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"boundary\"\r\n";
// Open the file for attachment
$file = fopen('uploads/' . $file_name, 'rb');
$data = fread($file, filesize('uploads/' . $file_name));
fclose($file);
// Encode the file data
$attachment = chunk_split(base64_encode($data));
// Add attachment to the email
$message = "--boundary\r\n";
$message .= "Content-Type: application/octet-stream; name=\"$file_name\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment; filename=\"$file_name\"\r\n\r\n";
$message .= $attachment . "\r\n";
$message .= "--boundary--";
// Send the email with attachment
mail('recipient@example.com', 'Subject', 'Message with attachment', $headers . $message);
}
?>
Related questions
-
private constants PHP classes code readability
-
Parse error unexpected T_VARIABLE PHP
-
security risks sensitive data external files