I have a basic form consisting of input fields as well as a file field. I have a few things that I want the form to do. Collect the information (obviously). There’s also an option to upload a file, (probably .doc,.pdf,.docx), so I want to restrict the attached file only to those extensions and under 2MB. All I know is that I have to have my form “enctype=multipart”, but that’s all I know.
I have the following PHP code:
<?
$to = 'my@email.com';
$subject = 'Contact from your website';
$message = 'From: ' . "\n\n" . 'Name: ' . $_REQUEST['name'] . "\n\n" . 'E-mail: ' . $_REQUEST['email'] . "\n\n" . 'Comments: ' . $_REQUEST['comments'];
$email = $_REQUEST['email'];
$headers = 'From: ' . $email . "\r\n" .
'Reply-To: ' . $email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/plain; charset=ISO-8859-1";
$str = $_REQUEST['email'];
if( $str == "E-mail address" || $str == "" )
{
echo "Please use your browser's back button enter a valid E-mail address";
} else {
mail ($to, $subject, $message, $headers);
header("Location: thankyou.html");
}
?>
How can I tweak it to allow it to send the attached file?
If possible, I’d love to see examples. Please understand that I’m extremely new to PHP, and until now have not needed to send PHP web forms with an attachment. So all that I ask of you is that if you post an example, please try to clarify the respective HTML form code that will work with the example.
Any help would be greatly appreciated!
Thanks a lot,
Amit
To mail an attachment, you can either use framework methods, or write the method yourself. Some sample code can be a good point to start.
To get a file sent from the browser, you have to use FILE variable. PHP documentation explains quite well how to do it.
To restrict file types to .doc and .pdf, you have to read the beginning of the file and compare to a “real” .doc or .pdf. An easier way would be to compare file extension, but the user of your website can always rename virus.exe to document.pdf.