Secure email in php

PHP secure mail

If no preventive measures are taken while coding a contact or feedback form in php, the code can be used by spammers to spam others. In this page, we will discuss how to write php mailing code so that it can not be compromised to spam.

A typical php code for mailing:

A PHP script for sending email calls mail() function to deliver the email. The code looks like this:

Where [email protected] is the address of the webmaster and $message and $email are a message and email collected from the feedback or contact form.
Unless preventive measures are taken, it is possible for a spammer to inject additional headers into the email messages by placing lines like the following into the $email variable

When this code is executed, all the email addresses added to the list are going to receive mails, which is unintended and will solve the purpose of the spammers.

How to write a secure code for mailing with php:

if ( preg_match( «/[\r\n]/», $usr ) || preg_match( «/[\r\n]/», $email ) ) <
header(«location : http://www.example.com/mail-error.php»);
>

Here, preg_match function will check of the user name (stored in $usrname) and email (stored in $email) contains any newline characters. If newline characters are found, then somebody trying to compromise the script to spam. In that case, the code will redirect to a page like http://www.example.com/mail-error.php instead of sent mail.

Читайте также:  Style type file html

Previous: PHP mail function
Next: PHP File Upload

Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

Detecting request type in PHP (GET, POST, PUT or DELETE)

if ($_SERVER['REQUEST_METHOD'] === 'POST') < // The request is using the POST method >

For more details please see the documentation for the $_SERVER variable.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

How to secure a simple PHP script that sends emails?

For E-mail bots check your page source to hide any e-mails readable for bots like something this: Encrypt mailto email addresses with inline JavaScript Question: first of all thank you for your time and helping me on this. i.e. will it stop bots, curl scripts sending spam using it, and stop email injections etc etc?

How to secure a simple PHP script that sends emails?

In a simple contact form, the HTML form triggers a Php script :

This email.php sends me an email :

The HTML is using jQuery validate plugin, but nothing like this on the Php side.

A Security expert told me how insanely unsecure this php script was .

What can I do to enhance security ?

My guess is that your «security expert» saw you using raw $_POST data and using the mail() function, and he freaked out, but didn’t stop to actually check how bad things were.

He has a point in that using $_POST without doing any validation on it is almost always a recipe for being hacked, but in fact in this particular case I don’t think it’s too bad, because you are the only recipient (so it’s not going to be used for spam, which is the main thing to worry about in these cases), and because the body is plain text (so a hacker can’t send you any nasty scripts or attachments).

Without any validation, you could get some really weird emails as a result of hackers trying to find a way around your defences, but not too much else.

PHP’s mail() function is a well-known soft target for hackers because there is an awful lot of insecure code out there that uses it. However the real danger with mail() tends to be if you use the headers parameter (ie to set things like the sender address, etc), which you haven’t used. Since you’re not using headers , the risks are a lot lower, and mainly limited to making it easy for someone to mailbomb you.

If you are still worried about the security of the mail() function, the best solution is to use a library like phpMailer instead.

To be honest, my advice whenever anyone wants to use PHP’s mail() function is always to use phpMailer or Swiftmailer instead. And it’s not even just about security; even for simple cases, they can make your code a lot easier to read and maintain.

One big flaw is that an attacker could trivially fill your inbox with malicious or junk messages which, besides being very annoying, would likely cause Google to put your domain on their spam list.

They could do this by writing a short script to call that PHP function with some arbitrary data, and loop through it for however long they want.

This is an alternative way of solving what you asking for. And I hope this can be useful for other askers, as I see similar questions coming op consecutively.

If you intend to make professional application and focus on your core business, then I suggest you use some secured email portals with API from like mailgun, mandrill or others. Both service offer a dash board where you can see e-mail status of how many emails are sent and delivery status, and a lot of other statistics. It is FREE for small usage. It is worth it using it, because you will solve some of following issues:

  • You do not need to think about maintaining security of your smtp server
  • Or even correct configuring your smtp
  • Solving block and black IP addresses
  • Server attack
  • Spam problem
  • And name the more

Both solutions provide API for PHP or other platforms.

Note: I have been my self used my own smtp server few years back, and you know all the time I put to fixing and maintaining the smtp server is not worth it, because I could spent that time doing better stuff and leave e-mail service part for professionals.

PHP Email Contact Form, Build a simple HTML contact form (with optional CSS) and embed it on our website · Write a PHP script that will effectively handle sending emails

Use PhpMailer to Send Email in PHP

How to Send an Email in PHP using PHPMailer

How To Create A Forgotten Password System In PHP

How to secure a form which sends out emails

I have the following code which sends emails out.

Is this good/secure enough for a production environment. i.e. will it stop bots, curl scripts sending spam using it, and stop email injections etc etc?

is_valid) < // What happens when the CAPTCHA was entered incorrectly die ("The reCAPTCHA wasn't entered correctly. Go back and try it again. " . "(reCAPTCHA said: " . $resp->error . ")"); > else < require 'class.phpmailer.php'; //Create a new PHPMailer instance $mail = new PHPMailer(); //Set who the message is to be sent from $mail->SetFrom('oshirowanen@localhost.com'); //Set who the message is to be sent to $mail->AddAddress($_POST['email']); //Set the subject line $mail->Subject = 'subject goes here'; //Replace the plain text body with one created manually $mail->Body = $_POST['message']; //Send the message, check for errors if(!$mail->Send()) < die ("Mailer Error: " . $mail->ErrorInfo); > else < echo "Message sent!"; >> ?> 

So basically, what I am asking is, is the above code safe enough, secure enough, good enough for a production environment?

I haven’t used php mailer before but it should take care of safety, escaping, etc.
Your code looks good however:

    I would improve the script by adding an encoding check before sending — for example like this:

iconv("UTF-8", "UTF-8//IGNORE", $subject_or_message_or_any_string); 
if (!$mail->Send()) < LogErrorMessage("Mailer Error: %s", $mail->ErrorInfo); die ("Sorry, mail could not be sent"); > 

I would suggest 2 more options:

I.) You can put extra input txt fields in your sending form, and then make them hidden (unseen) for the user with css styles, f.e.

II.) You can create a list of users (with their IP’s, Names, Cookie-ID’s, user-ID’s, if they sent email when were authorized on the site etc.) and prevent them from sending similar email’s several times in a row (in some short period of time). You can also implement some rules to filter spam bots. F.e., if user tries sending too often, then it could be blocked. Another option is to have a «white list» of authorized users, who would be able to send mails with more freedom and wider restrictions.

For those who doesn’t know what header injection (called by OP email injection) is: Even if we assume captcha is uncrackable, a human can fill your form, add some spam comment, and insert a BCC header with thousands of e-mail addresses and your script will send them.

So you should not allow any newlines in any of the headers (to, subject)

PHPMailer takes care of this, here is the relevant part of the code:

$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim if (!$this->ValidateAddress($address)) < $this->SetError($this->Lang('invalid_address').': '. $address); 

Recaptcha is breakable, and some spam can be send. You are effectively limiting the spam, but if it’s important not to allow any spam, then you need a spam filter on the content of the e-mail, as you can never guarantee that the form will not be send by a human, who wants to send some spam messages. Or you can add a limit of messages send from a given IP per hour so you will effectively limit the amount of spam messages that can be send, even if the captcha is cracked or a human is filling it. And you may add a check so the same message content can’t not be send to more than X addresses. This is if it’s a popular server and it’s really important to protect it from sending spam messages; for general use your code is good enough.

reCaptcha is a good anti-spam script. For E-mail bots check your page source to hide any e-mails readable for bots like something this: encrypt mailto email addresses with inline javascript

How to properly use PHPMailer, I created a forgot password system also but when I activate the php code that sends the actual email using PHPMailer I get an HTTP ERROR 500

Phpmailer secure approach by placing credentials out of the web root in INI file

first of all thank you for your time and helping me on this. I have a simple contact form and i’m using phpmailer.

I want to store credentials in an INI file out of webroot and then include it in my mail.php file which is the mail sending script.

How to write the INI content and how to call them on mail.php file?

This is my HTML file which is contact us form:



and this is the email.php file:

 CharSet = 'UTF-8'; $mail->IsSMTP(); $mail->Host = "localhost"; $mail->SMTPAuth = true; $mail->Username = "info@example.com"; // SMTP username $mail->Password = "this is the password"; // SMTP password $mail->From = $email; $mail->AddAddress("info@example.com"); $mail->WordWrap = 50; $mail->IsHTML(true); $mail->Subject = $ddomain; $mail->Body = $message; $mail->AltBody = $ddomain; if(!$mail->Send()) < echo "Error 

"; echo "Mailer Error: " . $mail->ErrorInfo; exit; > echo "we have received your email"; ?>

I want to store credentials in a safe place.

Another problem is that whenever someone open email.php file in browser ( example.com/email.php) an empty email will be sent to me, how to prevent it? I want the email.php file to be executed only a result of a customer’s contact via filling the form and not by directly opening the email.php file

 $constants = parse_ini_file("/outside/web/sample.ini"); header('Content-type: text/plain; charset=utf-8'); $email = $_REQUEST['demail'] ; $message = $_REQUEST['dmessage'] ; $ddomain = $_REQUEST['ddomain'] ; require("PHPMailer_v5.1/class.phpmailer.php"); $mail = new PHPMailer(); $mail->CharSet = 'UTF-8'; $mail->IsSMTP(); $mail->Host = "localhost"; $mail->SMTPAuth = true; $mail->Username = $constants['username']; // SMTP username $mail->Password = $constants['password']; // SMTP password $mail->From = $email; $mail->AddAddress("info@example.com"); $mail->WordWrap = 50; $mail->IsHTML(true); $mail->Subject = $ddomain; $mail->Body = $message; $mail->AltBody = $ddomain; if(!$mail->Send()) < echo "Error 

"; echo "Mailer Error: " . $mail->ErrorInfo; exit; > echo "we have received your email"; ?>

INI file (sample.ini) looks like:

username = "info@example.com" password = "PASSW0RD" 

Thank you for your helps. I did some change on your code and it is excatly what is want. instead of saying:

if (empty($_REQUEST['demail']) || empty($_REQUEST['dmessage']))
 if (empty($_REQUEST['demail']) || empty($_REQUEST['dmessage']))

Php — PHPMailer, I have also faced the same issue. I just found a less secure app function that got disabled by google and it’s no longer accessable.

Источник

Оцените статью