- How to create PHP based email form with file attachment
- The HTML form with file upload box
- Getting the uploaded file in the PHP script
- Validating the size and extension of the uploaded file
- Copy the uploaded file
- Sending the Email
- The sample PHP upload form
- How to Install the PEAR Library
- See Also
- PHP | Send Attachment With Email
- Отправка файла по e-mail на PHP
- Комментарии ( 20 ):
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.
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:
while defining the 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; $isizeof($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 code above, 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 contains 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
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:
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”.
See Also
PHP | Send Attachment With Email
Sending an email is a very common activity in a web browser. For example, sending an email when a new user joins a network, sending a newsletter, sending greeting mail, or sending an invoice. We can use the built-in mail() function to send an email programmatically. This function needs three required arguments that hold the information about the recipient, the subject of the message and the message body. Along with these three required arguments, there are two more arguments which are optional. One of them is the header and the other one is parameters.
We have already discussed sending text-based emails in PHP in our previous article. In this article, we will see how we can send an email with attachments using the Mime-Versionmail() function.
When the mail() function is called PHP will attempt to send the mail immediately to the recipient then it will return true upon successful delivery of the mail and false if an error occurs.
Syntax:
bool mail( $to, $subject, $message, $headers, $parameters );
Here is the description of each parameter.
Name | Description | Required/Optional | Type |
---|---|---|---|
to | This contains the receiver or receivers of the particular email | Required | String |
subject | This contains the subject of the email. This parameter cannot contain any newline characters | Required | String |
message | This contains the message to be sent. Each line should be separated with an LF (\n). Lines should not exceed 70 characters (We will use wordwrap() function to achieve this.) | Required | String |
headers | This contains additional headers, like From, Cc, Mime Version, and Bcc. | Optional | String |
parameters | Specifies an additional parameter to the send mail program | Optional | String |
When we are sending mail through PHP, all content in the message will be treated as simple text only. If we put any HTML tag inside the message body, it will not be formatted as HTML syntax. HTML tag will be displayed as simple text.
To format any HTML tag according to HTML syntax, we can specify the MIME (Multipurpose Internet Mail Extension) version, content type and character set of the message body.
To send an attachment along with the email, we need to set the Content-type as mixed/multipart and we have to define the text and attachment sections within a Boundary.
Approach: Make sure you have a XAMPP server or WAMP server installed on your machine. In this article, we will be using the WAMP server.
Follow the steps given below:
Create an HTML form: Below is the HTML source code for the HTML form. In the HTML tag, we are using “enctype=’multipart/form-data” which is an encoding type that allows files to be sent through a POST method. Without this encoding, the files cannot be sent through the POST method. We must use this enctype if you want to allow users to upload a file through a form.
Отправка файла по e-mail на PHP
В этой статье я собираюсь осветить тему отправки файлов по e-mail на PHP. Задача эта весьма популярная, а вот многие не знают, как это делается и научились только отправлять обычные письма без вложенных файлов. Этот пробел я постараюсь заполнить.
Я написал скрипт, который Вы смело можете копировать и использовать в своих скриптах. Данный код позволяет отправлять файлы по e-mail через PHP:
$filename = «form.txt»; //Имя файла для прикрепления
$to /cdn-cgi/l/email-protection» data-cfemail=»2b4a49486b464a424705595e»>[email protected]»; //Кому
$from /cdn-cgi/l/email-protection» data-cfemail=»dfbbbab99fb8b2beb6b3f1bcb0b2″>[email protected]»; //От кого
$subject = «Test»; //Тема
$message = «Текстовое сообщение»; //Текст письма
$boundary = «—«; //Разделитель
/* Заголовки */
$headers = «From: $from\nReply-To: $from\n»;
$headers .= «Content-Type: multipart/mixed; boundary=\»$boundary\»»;
$body = «—$boundary\n»;
/* Присоединяем текстовое сообщение */
$body .= «Content-type: text/html; charset=’utf-8’\n»;
$body .= «Content-Transfer-Encoding: quoted-printablenn»;
$body .= «Content-Disposition: attachment; filename==?utf-8?B?».base64_encode($filename).»?=\n\n»;
$body .= $message.»\n»;
$body .= «—$boundary\n»;
$file = fopen($filename, «r»); //Открываем файл
$text = fread($file, filesize($filename)); //Считываем весь файл
fclose($file); //Закрываем файл
/* Добавляем тип содержимого, кодируем текст файла и добавляем в тело письма */
$body .= «Content-Type: application/octet-stream; name==?utf-8?B?».base64_encode($filename).»?=\n»;
$body .= «Content-Transfer-Encoding: base64\n»;
$body .= «Content-Disposition: attachment; filename==?utf-8?B?».base64_encode($filename).»?=\n\n»;
$body .= chunk_split(base64_encode($text)).»\n»;
$body .= «—«.$boundary .»—\n»;
mail($to, $subject, $body, $headers); //Отправляем письмо
?>
Скрипт достаточно хорошо прокомментирован, но я добавлю ещё один важный момент. Обратите внимание, что если идут вложенные файлы, то текст письма нужно тоже делать, как прикрепление к письму, однако, тип содержимого будет другой. Это весьма серьёзная особенность, если не сделать так, то текст письма отправлен не будет. Это очень частая ошибка, поэтому обратите на это особое внимание.
Данный PHP-скрипт для отправки файлов по e-mail сделан максимально коротким, он универсален, поэтому Вы можете его дорабатывать под свои нужды так, как пожелаете.
Создано 06.01.2012 16:07:44
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
- Кнопка:
Она выглядит вот так: - Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт - BB-код ссылки для форумов (например, можете поставить её в подписи):
Комментарии ( 20 ):
Михайл Русаков ;). Со светлым Рождеством Христовым! Я тебя очень прошу каждые исходники и добавить и покажи «Результат данного примера показан» например как у htmlbook.ru Я тебя предлагаю мое мнение это удобно видеть примеры и все будет понял. Заранее спасибо большое ;). Удачи.
У вас ошибочка! Написано «Данная код» Вы наверное имели ввиду «Данный код»