How can PHP developers troubleshoot issues related to sending email attachments through contact forms?
Issue: PHP developers can troubleshoot issues related to sending email attachments through contact forms by ensuring that the file paths are correct, checking the file size limit set in the PHP configuration, and verifying that the email server supports attachments.
// Example PHP code snippet to send email with attachment
$to = "recipient@example.com";
$subject = "Test Email with Attachment";
$message = "This is a test email with attachment.";
$attachment_path = "/path/to/attachment/file.pdf";
$attachment_filename = "file.pdf";
$from_email = "sender@example.com";
$from_name = "Sender Name";
$boundary = md5(uniqid(time()));
$headers = "From: $from_name <$from_email>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";
$message = "--$boundary\r\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$message .= $message."\r\n";
if(file_exists($attachment_path)){
$file = file_get_contents($attachment_path);
$message .= "--$boundary\r\n";
$message .= "Content-Type: application/pdf; name=\"$attachment_filename\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment; filename=\"$attachment_filename\"\r\n";
$message .= base64_encode($file)."\r\n";
$message .= "--$boundary--\r\n";
}
// Send the email
$mail_sent = mail($to, $subject, $message, $headers);
if($mail_sent){
echo "Email sent successfully with attachment.";
} else {
echo "Failed to send email with attachment.";
}