How to attach file with feedback form in PHP ?

To attach a file with a feedback form in PHP, you can use the PHP mail() function along with the multipart/form-data encoding type in the HTML form. Here are the steps to do it:

  • Create an HTML form with the enctype attribute set to multipart/form-data to allow file uploads. For example:
<form action="submit.php" method="post" enctype="multipart/form-data">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name"><br><br>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email"><br><br>
  <label for="message">Message:</label>
  <textarea id="message" name="message"></textarea><br><br>
  <label for="attachment">Attachment:</label>
  <input type="file" id="attachment" name="attachment"><br><br>
  <input type="submit" value="Submit">
  • In the PHP script that handles the form submission (submit.php in this example), use the $_FILES superglobal to access the uploaded file. For example:
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$attachment = $_FILES['attachment'];

// Process the form data and send the email with attachment using the mail() function
  • Use the fopen() function to open the uploaded file and read its contents. For example:
$attachment_name = $attachment['name'];
$attachment_tmp_name = $attachment['tmp_name'];
$attachment_type = $attachment['type'];
$attachment_size = $attachment['size'];

$attachment_content = file_get_contents($attachment_tmp_name);
$attachment_content = chunk_split(base64_encode($attachment_content));
  • Use the boundary parameter to separate the different parts of the email message, including the attachment. For example:
$boundary = md5(time());

$headers = "From: $email\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";

$message_body = "--$boundary\r\n";
$message_body .= "Content-Type: text/plain; charset=\"UTF-8\"\r\n";
$message_body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
$message_body .= "$message\r\n\r\n";

$message_body .= "--$boundary\r\n";
$message_body .= "Content-Type: $attachment_type; name=\"$attachment_name\"\r\n";
$message_body .= "Content-Transfer-Encoding: base64\r\n";
$message_body .= "Content-Disposition: attachment; filename=\"$attachment_name\"\r\n\r\n";
$message_body .= "$attachment_content\r\n\r\n";

$message_body .= "--$boundary--";

mail('[email protected]', 'Feedback Form Submission', $message_body, $headers);

This will send an email with the form data and the attached file to the specified recipient. Note that you may need to adjust the email headers and message body to fit your specific requirements.

About the author

William Pham is the Admin and primary author of With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.