Attaching Selected Files

The Advanced Email Script allows you to specify a list of files to be attached as a comma separated list in a form field called "attach". This can be easily set up as a hidden field if you have a specific list of files you want to have attached. It can also be easily set up as an input text field if you want the person filling out the form to enter the files to be attached. You can even allow them to attach local files from their own computer.

Another alternative is to have a predefined list of files on your server that can be attached to an email and have the person filling out the form decide which of those files to attach to the email by selecting them using checkboxes. This involves slightly more code than if we just allow them to enter the names themselves but makes sure that only the specified files can be selected.

The first thing that we need in order to set this up is to use a different field name from "attach" to set up an array of checkboxes in our form. Let's use "file" for this. We next define each of the checkboxes in our form. They will look like this with the file names of the files that we want attached in the value attribute.

<input type="checkbox" name="file[]" value="doc1.pdf" />

We just repeat that as many times as we need to for the different files changing the filename in each and specifying the appropriate labels so that the person filling out the form knows what each checkbox will select.

To get this to create the "attach" field for our email to attach all of the correct files we will need to convert this array into a comma separated list. To do this we need to add a few lines of PHP into an include file attached into the form. To attach the include file we need to add the following to the form.

<input type="hidden" name="include" value="attach.php" />

Now all we need to do is to create the attach.php file and upload it to the same folder as the email script. The attach.php file needs to have the following contents in order to convert the file array into thew needed attach field and to remove the file array from the list of text fields being processed by the form.

$attach = implode($_POST['file'],',');
for ($i = 0; $i < sizeof($f_ks); $i++) {
   if ($f_ks[$i] == 'file') {
      array_splice($f_ks, $i, 1);
      array_splice($f_vs, $i, 1);

As long as the values in the checkbox fields represent the actual file names of the files to be attached then whichever checkboxes are selected will determine the list of files to be sent with the email.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow