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
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".
No related posts.




{ 84 comments }
← Previous Comments
Next Comments →
So sad, no body explain or leave a comment regarding the installation of Mail.php & Mail/Mime.php
Did Khin bother to read the text:
”
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”.
By installing those packages into PEAR via the web interface, you get both includes.
Let me know, what framework did u use?
Please show me how to install Mail.php & Mail/Mime.php
It’s easy just goto http://pear.php.net/package/Mail_Mime/download
Download the file, upload Mail_Mime/Mime.php to your server.
Then goto http://pear.php.net/package/Mail/download
Do the same for that one.
Make sure you test php on your server not on your computer.
if you install PEAR and wanna install packages you just go to http://www.yourwebsite.com/PEAR/pearfrontendweb.php
Then you can seach for packages mail & mail_mine and install these.
Grz
I got mine to work but the only downfall is if you get any errors it will wipe each input box clean, and they would have to retype everything
Anyone know how to change that?
I take that back, it’s only when the file you attached is too large or an incorrect file type, if so it tells you but wipes all input boxes clean. Anyone know what’s up?
Nice and helpful article i must say

You are good no doubt about this.
I also found http://www.7tech.co.in/php/send-mail-with-or-without-attachment-by-using-php/ good like your
Haven’t managed to get this script fully working yet – I’ve updated mail_mime.php to mail/mime.php, and replaced line 82 with
as some people suggested as a fix, and while it changed the error code I was getting, there’s something about that line that’s broken for me – it turns up this error message:
Warning: Unexpected character in input: ‘\’ (ASCII=92) state=1 in /hermes/web12a/b1229/moo.floathousebookscom/php-form-action.php on line 82
Parse error: syntax error, unexpected T_STRING in /hermes/web12a/b1229/moo.floathousebookscom/php-form-action.php on line 82
Can anyone help me here?
Thanks a lot, Wilf
I’ve been nabbing code bits off message boards for a long time so time to give back. Spent a long time sorting this out so here’s the solutions the this issue. Couple things:
1. ”\r\n” goes in the parens in line 81 in the version of the code I have. This whole line should look like this:
$message = new Mail_mime($crlf =”\r\n”);
When I copied and pasted “\r\n” into my php file from this web page is pasted in text quote characters instead of programatic quote characters. Delete them out and type them back in in your code editor. This is what is throwing the syntax error
2. The paths to your PEAR files should look like this
include_once(‘Mail.php’);
include_once(‘Mail/mime.php’);
but you also need to set the path to your PEAR Packages on your server in your php.ini
My hosting company is BlueHost and here are their instructions on how to do this.
install default php.ini file -> https://my.bluehost.com/cgi/help/128?step=128
Configure path to Pear Package in php.ini -> https://my.bluehost.com/cgi/help/533?step=533
-Steventre
Great step-by-step tutorial. Also we can create css stylesheet and make this form design as we wish.
For those who have problems with installing PEAR check your hosting providers. I used HostMonster and I didn’t have to download anything, just simply login to your Cpanel and clik one button.
less troubleshooting more success! In my case all files were created instantly in PHP not PEAR. Thanks for awesome tutorial!
The problem I am having is that the form cannot find the Pear files. I’ve tried using
<?php
ini_set(‘include_path’, ‘~/pear/lib’ . PATH_SEPARATOR
. ini_get(‘include_path’));
// From PHP 4.3.0 onward, you can use the following,
// which especially useful on shared hosts:
set_include_path(‘~/pear/lib’ . PATH_SEPARATOR
. get_include_path());
?>
in front of the form, but it still can’t find it.
$mail->send($to,$headers,$body);What is $to ? is it same as$visitor_email? if it is then what is the purpose because its already wraaped in mail contents?Thanks,Gaurav
I have never used php before, but I really need this to work. I have changed the email address and created a folder called ‘upload’ with permissions for everyone to edit. I have also installed PEAR, PEAR:Mail and PEAR:Mail_Mime and I don’t get any error messages when I run the script. When I submit something the image appears in my ‘upload’ folder, but I never receive an email.
Anyone have any tips on what I can try?
try with a different email address. Also, your php mail configuration could be bad.
Thank so much for explain how to send mail. This article was very usefull for me. I change some fragments, becouse i dont want to use pear to send. Good job
What actually “777″ permissions means. How to check it whether my sever has got the permission or not
see chmod
good
I got the email to work and attached files to work. The only thing that’s bothering me is the validation for the file type. I don’t mind the validation happening after submit, but rather the output message. I rather have a box come up rather than the error message populate on the page and push my form down. Is there a way to move the file type and size error to somewhere else or in a pop up box?
as i am new to php i will take some time to understand what you all are sayibg till the i wil read the comments and practice them
Is it nessecary to upload the file to the server, or can we just send it without storing it? I haven’t yet gotten it running, but would like to use:
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
$message->addAttachment($tmp_path);
Thank goodness there’s 1 tutorial out there that makes sense! You’re freaking awesome!
I’m getting this error message. I have the PEAR installed. Can you please help
Fatal error: Class ‘Mail_mime’ not found in /home/xxxxx/public_html/emailform.php on line 84
On line 84 is: $message = new Mail_mime();
Thanks
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? (I’m new. Have a computer science background but no web.)
Thanks!
Do you have PHP installed?
← Previous Comments
Next Comments →
Comments on this entry are closed.