How to attach file with feedback form in PHP ?
Feedback form is used to get the review from the user through mail services. Mailing is one of the server-side utilities that is required in most of the web servers today. In PHP, mail() is the built-in function that is used to send emails from PHP scripts either in a plain-text form or formatted HTML. You can also write a script to attach any files into your mail from send Attachment With Email article.
The PHP mail function has the following basic Syntax:
<?php mail($to_email_address, $subject, $message, [$headers], [$parameters]); ?>
Attaching file in feedback form: To send an email with attachment as feedback, we need to use the multipart/mixed MIME type(set Content-type header to multipart/mixed) that specifies that mixed types will be included in the email. Moreover, we want to use a multipart/alternative MIME type to send both plain-text and HTML versions of the email. Text and attachment sections can be specified within boundaries. A boundary is started with two hyphens followed by a unique number that can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create a unique number. A final boundary denoting the email’s final section must also end with two hyphens.
To include an attachment to our message, we read the data from the specified file into a string, encode it with base64_encode() function for safer transmission, split it in smaller chunks with the chunk_split() function to make sure that it matches the MIME specifications and then include it as an attachment.
- Feedback form GUI:
- After receiving mail:
Using mail() on localhost on XAMPP: Sending mail from the localhost can be done using Sendmail package, Sendmail package is inbuild in XAMPP.
- Step 1: In C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.
- Step 2: In php.ini file find [mail function] and change
SMTP=smtp.gmail.com smtp_port=587 sendmail_from = email@example.com sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
- Step 3: In C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code:
[sendmail] smtp_server=smtp.gmail.com smtp_port=587 error_logfile=error.log debug_logfile=debug.log firstname.lastname@example.org auth_password=gmail-password email@example.com
- Step 4: Change firstname.lastname@example.org and gmail-password as required. Restart the server the XAMMP control panel so the changes take effect.
- Step 5: Create a php file and send mail.
Note: However, the PHP mail() function is a part of the PHP core but you need to set up a mail server on your machine to make it really work.