How to create PHP based email form with file attachment

This article shows you how to create a PHP based email form that supports file attachment. The article will also show you how to validate the type and size of the uploaded file.

Note: It is easy to create complete file upload forms using Simfatic Forms. Visually design the form, get form submissions by email, save submissions to database and more. No coding required. Read more about Simfatic Forms here.

The HTML form with file upload box

The code for an HTML form with a file upload box is given below. User can click on the ‘Browse’ button to select the file from his/her local machine.

<form method="POST" name="email_form_with_php"
action="php-form-action.php" enctype="multipart/form-data"> 

<label for='name'>Name: </label>
<input type="text" name="name" >

<label for='email'>Email: </label>
<input type="text" name="email" >

<label for='message'>Message:</label>
<textarea name="message"></textarea>

<label for='uploaded_file'>Select A File To Upload:</label>
<input type="file" name="uploaded_file">

<input type="submit" value="Submit" name='submit'>
</form>

The form will look like this:

Please note that we have added:

"enctype="multipart/form-data"

while defining the <form> tag. This is to tell the browser that this form will be used to upload files. Then we have added the “name” and “email” fields to collect the user info. The third form field is the file upload box.

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

On hitting the “Submit” button, the form data along with the file data is posted to the script pointed to by the ‘action’ attribute of the form.

Getting the uploaded file in the PHP script

In the PHP script, we will first validate the submission and if the validation succeeds, we will send the submission by 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. The code below gets the name, type and size of the uploaded file:

//Get the uploaded file information
$name_of_uploaded_file =
    basename($_FILES['uploaded_file']['name']);

//get the file extension of the file
$type_of_uploaded_file =
    substr($name_of_uploaded_file,
    strrpos($name_of_uploaded_file, '.') + 1);

$size_of_uploaded_file =
    $_FILES["uploaded_file"]["size"]/1024;//size in KBs

The code above is getting the different attributes of the uploaded file from the $_FILES[] array.

Validating the size and extension of the uploaded file

Suppose we don’t want to allow files greater than the size of 100KB and we only want to allow image files to be uploaded. The validation code goes like this:

//Settings
$max_allowed_file_size = 100; // size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp");

//Validations
if($size_of_uploaded_file > $max_allowed_file_size )
{
  $errors .= "\n Size of file should be less than $max_allowed_file_size";
}

//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
  if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
  {
    $allowed_ext = true;
  }
}

if(!$allowed_ext)
{
  $errors .= "\n The uploaded file is not supported file type. ".
  " Only the following file types are supported: ".implode(',',$allowed_extensions);
}

In the above code we are validating the file size and type. We have the maximum allowed file ($max_allowed_file_size) size set to 100KB. The $allowed_extensions array cotains the file extensions of all allowed file types.
The validation code checks to see whether the file extension matches any of the extensions in the $allowed_extensions array.

If there are errors found in the validation, the error is displayed. Else we proceed with sending the email.

Copy the uploaded file

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 a folder on the server.

//copy the temp. uploaded file to uploads folder
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];

if(is_uploaded_file($tmp_path))
{
  if(!copy($tmp_path,$path_of_uploaded_file))
  {
    $errors .= '\n error while copying the uploaded file';
  }
}

This code copies the uploaded file to the ‘uploads’ folder. You can change the uploads folder by updating $upload_folder.
Please make sure that “uploads” folder has “777” permissions.

Sending the Email

The next step is to compose and send the email. We will use the Pear library for composing and sending the email. ( see the Pear installation instructions below ) The pear classes PEAR::Mail and PEAR::Mail_Mime are used for sending the email with the attachment.

First, we need to include the pear library files for these classes.

include_once('Mail.php');
include_once('Mail_Mime/mime.php');

The code below composes and sends the email

$message = new Mail_mime();

$message->setTXTBody($text);

$message->addAttachment($path_of_uploaded_file);

$body = $message->get();

$extraheaders = array("From"=>$from, "Subject"=>$subject,"Reply-To"=>$visitor_email);

$headers = $message->headers($extraheaders);

$mail = Mail::factory("mail");

$mail->send($to, $headers, $body);

Mail_mime() class helps in composing a MIME message. In the code above, a Mail_mime object is created, the text body is updated ( $message->setTXTBody($text); ) and the attachment is added ( $message->addAttachment(file) )

The MIME encoded message is then sent using the Mail class.

The sample PHP upload form

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

The download contains a complete PHP upload form that sends the uploaded by email.

How to Install the PEAR Library

In this article we 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. Then run this file from your browser, like this:

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

This display the web interface to install the PEAR on your website. The interface shows detailed instructions. After Pear is installed, search and install packages “mail” and “mail_mime”.

Also see: more free file upload forms from ReusableForms.com

Comments on this entry are closed.

  • Uhhh, I can’t belive how many stupid people are trying to write PHP…
    Just hear this “Do you have PHP installed?” , “I uploaded the pear script, but it doesn€™t €œrun€. When I go to it in my browser, it just shows the script as text. How do I get it to run?”
     
    Anyway your clever to choose PEAR for this job, the rest is bullshit, nice, nice, nice!
     
    PS: on Linux box to install needed PEAR modules (if you have installed peal already) exec as root: pear install Mail Mail_Mime

    • People who write PEAR write PHP.

  • Great tutorial, thank you. Can someone help me with my error though?
     
    Fatal error: No PEAR.php in supplied PEAR directory: @pear_dir@ in /home/content/31/8568731/html/index.php on line 24


    was there supposed to be a PEAR.php file in the zipped file?

  • Its working… Awesome….!! But how can I upload multiple files in contact form.
    Please help me.

    • Mubshir Gilani …. i have a question how did you get it to work i’m getting a not found in error message [ include_once(Mail_Mime/mime.php) [function.include-once]: failed to open stream: No such file or directory ]

      which directory did you up load it into?

      • ok so i got that last one fixed now i’m getting:

        ————————————————–
        Fatal error: Call to undefined method Mail_mail::_sanitizeHeaders() in /Mail/mail.php on line 121
        ————————————————–
        if anyone know hot to fix this one…..PLEASE HELP.

  • Hi guys,
    If the Pear is not installed, you can use the PHP mail functionality to send an attachment.
    The php function is available in the following url

    http://www.codelooms.com/2011/10/php-function-for-sending-attachment-mail/

    Tom

  • For those having problems with PEAR and the Modules. These will need to be either installed on your production server using the script as suggested http://pear.php.net/go-pear. If using virtual hosting or some other hosting environment your hosting company may well supply you with the include paths required as pear will probably already be installed.

    Jason
    Possibly your path to the pear directory is wrong. From a command line type
    pear config-show
    to get your correct paths…

  • When I upload I file I get this:

    Not Found
    The requested URL /php-form-action.php was not found on this server.

  • not everyone are using dedicated server or vps.most are using web hosting so we can’t install pear…

  • hello, first thanks for the script.
    i’m having a hard time to make the script work, i see that it does upload the file to the uploads dir but it won’t send the email. after hitting submit all i get is a blank page with number 0.
    i’ve check that the server does have mail and mail_mime installed.
    any ideas?

    thanks
    yaniv

  • Works fine but I have a small issue….. Increasing the $max_allowed_file_size to 10000 uploads the file to the specified folder but the mail is never sent!

    Any ideas?

    • The file size is probably too big to be emailed – 10mb is a pretty large file to email.

  • You’re the man, excellent tutorial – this has helped me tremendously in this learning voyage of mine through PHP.

    Total star – thank you so much.

    Regards

    Paul

  • very nice script

  • Its not working.. got this error.
    Bootstrapping Archive/Tar.php…………(remote)
    Fatal error: Class ‘PEAR’ not found in /hermes/bosweb/web151/b1515/ipg.

  • Works great! Thanks! I was wondering, however, what might need to be altered to make it handle multiple uploads/attachments? I’m sure I’m not the only one curious. Thanks!

  • Starting installation …
    Loading zlib: ok

    Bootstrapping Installer……………….
    Bootstrapping PEAR.php…………(remote) “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

    An Exception Has Occurred

    Unknown location: /pear/pear-core/branches/PEAR_1_4/PEAR.php

    HTTP Response Status

    404 Not Found

    ok
    Bootstrapping Archive/Tar.php…………(remote)
    Fatal error: Class ‘PEAR’ not found in /web/htdocs/mydirectory/temp/Archive/Tar.php on line 58

    What can I do?

  • Works great! Thanks! I was wondering, however, what might need to be altered to make it handle multiple uploads/attachments? I€™m sure I€™m not the only one curious. Thanks!

  • Hi, your script is exactly what I need but unfortunatley is not quite working. The form is there but when I click submit ti then goes to an error page advising that the url could not be found. Any help would be appreciated. Alternatively if you need other info then please contact me. Cheers

  • Warning: include_once(Mail_Mime/mime.php) [function.include-once]: failed to open stream: No such file or directory in /home/alkhaima/public_html/send-email-form.php on line 5

    Warning: include_once() [function.include]: Failed opening ‘Mail_Mime/mime.php’ for inclusion (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in /home/alkhaima/public_html/send-email-form.php on line 5

    Fatal error: Class ‘Mail_mime’ not found in /home/alkhaima/public_html/send-email-form.php on line 81

  • How to give attractive look in email. when i m send mail by my website then at receiver look not good. i want send logo and some text.

  • I’m getting this error. Please he me out

    Starting installation …
    Loading zlib: ok

    Bootstrapping Installer……………….
    Bootstrapping PEAR.php…………(remote) “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

    An Exception Has Occurred

    Unknown location: /pear/pear-core/branches/PEAR_1_4/PEAR.php

    HTTP Response Status

    404 Not Found

    ok
    Bootstrapping Archive/Tar.php…………(remote)
    Fatal error: Class ‘PEAR’ not found in /home/eap/public_html/test2100/temp/Archive/Tar.php on line 57

  • very help full for to it student(web designer and web devloper)