html form guide
  about

How to create PHP based email form with file attachment

This article shows how to create a php based email form that supports file attachment. The article will also show how to validate the type and size of the uploaded file. This tutorial will be based on two files. First page will be the HTML page with a file upload box. This page will allow the user to select a file from local machine. The second page will be the PHP page that will validate the uploaded file and will send it by email.

Sample HTML form with file upload box

Below is the sample HTML form with a file upload box. User can click on the 'Browse' button to select the file from his/her local machine. On clicking the Submit button the selected file will be uploaded to the server. We can name this HTML page as "attachment_email_form.html"

<HTML>
<HEAD><title>File Upload Form</title></HEAD>
<BODY>
<form method="POST" name="email_form_with_php" action="send-email-form.php" enctype="multipart/form-data">
Enter Name: <input type="text" name="name"><br>
Enter Message: <textarea name="message"></textarea><br>
Select A File To Upload: <input type="file" name="uploaded_file"><br>
<input type="submit" value="Submit"><br>
</form>
</BODY>
</HTML>

Please note that we have added:

"enctype="multipart/form-data"

while defining our FORM. This is to tell the browser that this form will be used to upload the files. Then we have added the "name" and "address" fields to collect the user info. The third and most important form field is the "FILE" field. You can see it like this in above code:

<input type="file" name="uploaded_file">

This HTML code will simply add a text box with a "BROWSE" button. On clicking the browse button, you can find and select a file from your computer.

On hitting the "Submit" button user will be taken to the PHP page namely "send-email-form.php".

Getting the uploaded file in the php script

In "send-email-form.php" we shall be doing the rest of work. In this file we shall get the uploaded file and validate its type and size etc. If the validation is passed, the uploaded file will be attached to send the email.

We can access the uploaded file and its different attributes by using the "$_FILES" array. This array will contain the name, size, path and other attributes of the uploaded file. Below is the code to get the name, type and size of the uploaded file:

<?php
list($name_of_uploaded_file, $type_of_uploaded_file, $size_of_uploaded_file) = GetUploadedFileInfo();

function GetUploadedFileInfo() {
   $file_info[] = basename($_FILES['uploaded_file']['name']);
   $file_info[] = substr($file_info[0], strrpos($file_info[0], '.') + 1);
   $file_info[] = $_FILES["uploaded_file"]["size"]/1024;
   return $file_info;
}
?>

We have created a function namely GetUploadedFileInfo(). This function is getting the different attributes of uploaded file by using the different values of $_FILES array. These attributes are stored in an array namely "$file_info". After the execution of this function the "$file_info" array is returned back and the values are asssigned to the appropriate variables by using the "List()" construct. The variable "$name_of_uploaded_file" is getting the name of uploaded file. The variable "$type_of_uploaded_file" is getting the extension of uploaded file. For example, its value will be "jpg" if the uploaded file is an image file. The variable "$size_of_uploaded_file" is getting the size of uploaded file. We have divided the size with 1024 to get the size in KBs.

Validating the size and extension of the uploaded file

We have got the size and extension of the uploaded file in the variables "$size_of_uploaded_file" and "$type_of_uploaded_file", respectively. Now, we shall just validate these variables. Suppose that we don't want to allow files greater than the size of 100KB and we only want to allow the jpg file (image file) to be uploaded. The code for these validations will be like this:

<?php
$max_allowed_file_size = "100"; // this is size in KB
$allowed_extension = "jpg";
$type_of_uploaded_file = strtoupper($type_of_uploaded_file);
$allowed_extension = strtoupper($allowed_extension);

if(!Validate($name_of_uploaded_file, $type_of_uploaded_file, $size_of_uploaded_file, $max_allowed_file_size, $allowed_extension)) {
   exit();
}

function Validate($name_of_uploaded_file, $type_of_uploaded_file, $size_of_uploaded_file, $max_allowed_file_size, $allowed_extension) {
   $type_of_uploaded_file = strtoupper($type_of_uploaded_file);
   $allowed_extension = strtoupper($allowed_extension);
   if($size_of_uploaded_file>$max_allowed_file_size ) {
      echo "Size of file is greater than" . $max_allowed_file_size . " KB. <a href='attachment_email_form.html'>Click Here to upload a smaller sized file.";
       return false;
   }
   $result = strcmp($type_of_uploaded_file, $allowed_extension);
   if(!($result==0)) {
       echo "You have uploaded a file with an extension of " . $type_of_uploaded_file . " . This type is not allowed. Please upload file with " . $allowed_extension ." extension. <a href='attachment_email_form.html'>Click Here to upload a file with allowed extension.";
       return false;
   }
    return true; }
?>

In the above code we are validating the file size and type. We have set the maximum allowed file ($max_allowed_file_size) size to 100KB. You can change it according to your needs. We have created a function called Validate(). We are passing 4 arguments to this function, namely $name_of_uploaded_file, $type_of_uploaded_file, $size_of_uploaded_file, $max_allowed_file_size. The more details of this function are as follows:

if($size_of_uploaded_file>$max_allowed_file_size ) {

This line of code is comparing the uploaded file size with maximum allowed file size. If size of uploaded file is greater than an error message is displayed and "false" is returned. Then exit() function is used to stop the further working of script.

$allowed_extension = array("jpg", "jpeg", "gif", "bmp");
for($i=0; $i<sizeof($allowed_extension); $i++) {
   $allowed_extension[$i] = strtoupper($allowed_extension[$i]);
}
$type_of_uploaded_file = strtoupper($type_of_uploaded_file); if(!(in_array(strtoupper($type_of_uploaded_file),$allowed_extension))) {    echo "You have uploaded a file with an extension of " . $type_of_uploaded_file . " . This type is not allowed. Please upload file with " . $allowed_extension ." extension. <a href='attachment_email_form.html'>Click Here to upload a file with allowed extension.";    return false; }

Here we are defining an array called "$allowed_extension". This array is containing all the extensions that are allowed to be uploaded. We have added the popular image extensions here. You can set this array according to your needs. We are using the "in_array" function to check if the extension of uploaded file is present in this array. If not found, an error message is displayed and "false" is returned and the script is stopped using the exit() function.

If the uploaded file is of right size with allowed extension, "true" will be returned by the above function and further process of file uploading will continue.

Composing the email and attaching the file to the email

Now, its time to send the uploaded file with the user message to the recipient's email address.

First of all we shall copy the file to an apropriate folder on the server. This will make the process easy. We have made a function namely "LoadUploadedFile()". This function is taking the name of uploaded file as an argument ($name_of_uploaded_file) and uploading the file in a folder namely "uploads".

Here is the code for this part.

<?php
function LoadUploadedFile($name_of_uploaded_file) {
   move_uploaded_file($_FILES["uploaded_file"]["tmp_name"], "uploads/" . $name_of_uploaded_file);
}
?>

The function "move_uploaded_file()" is just copying your uploaded file on your server in the "uploads" directory. Please make sure that "uploads" folder has "777" permissions.

Now we need to compose our email message and send the uploaded file by email. This all is done by calling a function namely "ComposeMail()". The different parts of this function are discussed below in detail. This function is is receiving one argument which is the path and name of the uploaded file.

Getting the User Info and Composing the Message

<?php
$name = $_POST['name'];
$user_message = $_POST['message'];
$to = "RecipientEmail@domain.com";
$subject="An email with attachment is sent";
$from = "someemail@domain.com";
$text = "A user " . $name . "has sent you this message and an attachment: " . $user_message;

?>

In the code above, we are just getting the values of "name" and "message" entered by user in the variables "$name" and "$user_message", respectively. "$to" variable is holding the email address at which the email will be sent. "$from" is holding the email address of sender. "$subject" is the subject of email. "$text" is holding the user name with his message. This will be the email text.

Now we shall use the classes PEAR::Mail and PEAR::Mail_Mime for sending attachment. The use of PEAR library makes it very easy to send the email with attachment.

Sending the Email

<?php
include_once('Mail.php');
include_once('mime.php');
$message = new Mail_mime();
$message->setTXTBody($text);
$message->addAttachment($name_of_uploaded_file);
$body = $message->get();
$extraheaders = array("From"=>$from, "Subject"=>$subject);
$headers = $message->headers($extraheaders);
$mail = Mail::factory("mail");
$mail->send($to, $headers, $body);
echo "Your Email with attachment was sent.";
?>

The first two lines of code are just including the two files, Mail.php and mime.php. These two files contain the classes PEAR::Mail and PEAR::Mail_Mime which contain all the important functions that will do our work. Make sure that you are using the correct path where these two file are located on your server. For using these classes you need to install the PEAR library on your server.

$message = new Mail_mime();

Here we are creating an instance of Mail_mime called "$message".

$message->setTXTBody($text);

In this line of code, we are setting the body of our email. We had stored the user message with details, in "$text" variable. Here we are using that variable to set the text of our email.

$message->addAttachment($name_of_uploaded_file);

Here we are calling a function addAttachement(). We have used the "$name_of_uploaded_file" as an argument. This will simply find the file and will attach it. This all is stored in "$message" variable.

$body = $message->get();
$extraheaders = array("From"=>$from, "Subject"=>$subject);
$headers = $message->headers($extraheaders); $mail = Mail::factory("mail");
$mail->send($to, $headers, $body);
echo "Your Email with attachment was sent.";

The body of the message will be stored in "$body" which is filled from the return value of message->get(). Now this $body variable contains the full message with attachment that is ready to be sent.

The "$extraheaders" is an array which is storing the "from email address" and "subject" of the email.

Now, we have the complete list of headers. This full info is passed into the send() call. "$to" is the email of recipient. "$headers" contains info like "subject" and "from email address" etc and other info. "$body" contains the full message for the user with the info about the attached file. This will simply send the email with attachment on your given email address.

Sample Code

Click here to download php-email-form-attachment.zip

The link above points to a single zip file. The zip file contains two files.First page is HTML page, namely "attachment_email_form.html", that is getting the user info and is used to upload the file from local computer. The second is the PHP file ("send-email-form.php") that is doing the rest of work. This file is getting the file and user data, validating the file size and type and attaching with email to send at the recipient email address. We are using the classes PEAR::Mail and PEAR::Mail_Mime for sending mail with attachment. The use of PEAR library makes it very easy to send the email with attachment.

How to Install the PEAR Library

In this article we have used the PEAR::Mail and PEAR::Mail_Mime classes to send the email with attachment. Before using these classes, you need to install the PEAR package on your server. It is beyond the scope of this tutorial to discuss the installation of PEAR. But, I want to give you a quick tip. Get the PEAR installer script from

http://pear.php.net/go-pear

Save the file as "pear-installer.php". Upload this file to your server in any directory. You can upload it in the root directory. Then run this file from your browser, like this:

http://www.yourdomain.com/pear-installer.php

This will give you the web interface to install the PEAR on your website. It includes all the instructions. Just use all the default settings. After it is installed, search for packages and install the "mail" and "mail_mime" classes. And thats it. Now you just need to include the files "Mail.php" and "mime.php" in your script to use the classes. Usually the Mail.php is in "PEAR" directory and mime.php is in "PEAR/Mail" directory.

  • Digg
  • del.icio.us
  • Netscape
  • Reddit
  • StumbleUpon
  • Technorati
  • YahooMyWeb



 
  • Digg
  • del.icio.us
  • Netscape
  • Reddit
  • StumbleUpon
  • Technorati
  • YahooMyWeb
Email forms
  How to get email from html form submission

Email form using 'mailto'

Form to email using PHP

Email form with file attachment in PHP

Form mail scripts
  Form mail script selection guide

Perl based form mail

Contact Forms
  PHP based email contact form

Secure your HTML contact form using captcha
PHP Form
  PHP form validation script

PHP form tutorial: first steps

PHP form processing

PHP form 'GET'

PHP form 'POST'

Handling checkbox in PHP form processor

Handling select box in a PHP form

Using PHP_SELF in the action field of a form

How to submit a form using PHP

Creating a registration form using PHP

Making a login form using PHP

Creating a multi-page order form using PHP

Passing PHP form variables from one page to other

  Copyright © 2008 html-form-guide.com . All rights reserved.