Following on from how to email a file already residing on your web server, I thought it would be best to next give your users the ability to choose a file on their local machine, and attach it to an email to send to you.
My current employer asked me to do this to allow disco lighting customers to upload a picture of their desired lighting rig, so we can give them a quote based on their drawing or mspaint art!
First we need a form for your user/customer to fill in.
<html>
<head>
<title>Mailer Form</title>
</head>
<body>
<form method="post" action="attach.php" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Nothing to fancy there. A simple file input form. I remember having problems if I didn’t use the id=”file” so be sure that is included.
The back of this will look very similar to the original email php script. But we will be making use of PHP’s $_FILES superglobal variable. Replace the static filename of our last example, with the more useful dynamic filename defined here.
email_attachment('to.this@address.com', 'my.email@address.com', 'Email attachment', 'My Name', 'my.email@address.com', $_FILES["file"]["tmp_name"]);
That will give you a very broad range of what can be temporarily uploaded to your site and what will end up in your email inbox. In your own scripts, you can use the $_FILES["file"]["type"] variable to check what sort of thing your user is uploading and prevent it if necessary. Remember to update $default_filetype as necessary.
<?php
if ($_FILES["file"]["type"] == "image/jpeg"){
email_attachment(...);
}else{
echo "Error";
}
?>
A few other useful variables are
$_FILES["file"]["name"] $_FILES["file"]["size"] $_FILES["file"]["error"]
A bit of experimentation with those will be easy enough.
Feedback on my blog posts is welcomed and encouraged!