Thursday, November 15, 2012

Easy to use and reliable mail function php

11/15/2012

How to send email with PHP. Although PHP has built in function mail() to send email, it's quite insecure and use nonobvious arguments. In below example function Send_mail can send mail when called with just four arguments: from, to, subject, text. To avoid email injection (using malformed parameters to send spam through mail()) removing of special characters is used.


<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

$site_admin = 'admin@example.com';

function Send_mail($from, $to, $subject, $text, $headers="")
{
    if (strtolower(substr(PHP_OS, 0, 3)) === 'win')
        $mail_sep = "\r\n";
    else
        $mail_sep = "\n";

    function _rsc($s)
    {
        $s = str_replace("\n", '', $s);
        $s = str_replace("\r", '', $s);
        return $s;
    }

    $h = '';
    if (is_array($headers))
    {
        foreach($headers as $k=>$v)
            $h = _rsc($k).': '._rsc($v).$mail_sep;
        if ($h != '') {
            $h = substr($h, 0, strlen($h) - strlen($mail_sep));
            $h = $mail_sep.$h;
        }
    }

    $from = _rsc($from);
    $to = _rsc($to);
    $subject = _rsc($subject);
    mail($to, $subject, $text, 'From: '.$from.$h);
}





if (($_SERVER['REQUEST_METHOD'] == 'POST') &&
    isset($_POST['subject']) && isset($_POST['text']) &&
    isset($_POST['from1']) && isset($_POST['from2']))
    {
        $from = $_POST['from1'].' <'.$_POST['from2'].'>';
        

        Send_mail($from, $site_admin, $_POST['subject'], $_POST['text'],
        array('X-Mailer'=>'4evertutorials.blogspot.in  Online PHP Examples with Source Code'));
        $mail_send = true;
    }



<html><head>Send us mail - 4evertutorials.blogspot.in
</head><body>
<?php
if (isset($mail_send)) {
    echo '

Form has been successfully sent, thank you

'; } else { ?>
Your Name:
Your Email:
Subject:
Text:
<?php } ?> </body></html> ?>

helpful? Share this

The Editorial Team of 4everTutorials consists of a group of PHP Professionals.

0 comments:

 

© 2014 4everTutorials. All rights resevered.

Back To Top