Jump to content


Photo

Some tweaks to the mailing script


  • Please log in to reply
5 replies to this topic

#1 SophieR

SophieR
  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 12 May 2017 - 05:56 AM

Hello!

I'm designing a website for a charitiy and I came across the problem I'm not able to solve, because I don't have enough knowledge of PHP. I hope someone here would be kind enough to help me out with what I'm trying to achieve...  :) 

On the website there is a form for a new members to send their personal data. The form itself works just fine, but I need to make some tweaks, to make it just a bit better. 

The HTML fields I'm using on a web template are:

 

- full name

- date of birth

- house adress

- post adress

- email

- phone

- nickname

- T-shirt size (dropdown menu)

- sticker color (dropdown menu)

Here is the PHP code I have to send the data:

<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');

// configure
$from = 'Demo contact form <info@email.com>';
$sendTo = 'Demo contact form <info@email.com>';
$subject = '<Data form: ';
$fields = array('name' => 'Full name:', 'birthday' => 'Birthday:', 'house_adress' => 'House adress:', 'post_adress' => 'Post adress:', 'email' => 'Email:', 'phone' => 'Phone mumber:', 'nickname' => 'Forums nickname:', 'shirt' => 'T-shirt size:', 'sticker' => 'Sticker color:' ); // array variable name => Text to appear in the email
$okMessage = 'Sample success message.';
$errorMessage = 'Sample error message. Try again later.';
$recaptchaSecret = 'xxx-xxxxxxxxxx_xxxxxxxxxx_xxxxxxxxxxxxx';

// let's do the sending

try
{
    if (!empty($_POST)) {

        // validate the ReCaptcha, if something is wrong, we throw an Exception, 
        // i.e. code stops executing and goes to catch() block
        
        if (!isset($_POST['g-recaptcha-response'])) {
            throw new \Exception('ReCaptcha is not set.');
        }

        // do not forget to enter your secret key in the config above 
        // from https://www.google.com/recaptcha/admin
        
        $recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
        
        // we validate the ReCaptcha field together with the user's IP address
        
        $response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);


        if (!$response->isSuccess()) {
            throw new \Exception('ReCaptcha was not validated.');
        }
        
        // everything went well, we can compose the message, as usually
        
        $emailText = "You have new message from contact form\n=============================\n";

        foreach ($_POST as $key => $value) {

            if (isset($fields[$key])) {
                $emailText .= "$fields[$key]: $value\n";
            }
        }
        

        $headers = array('Content-Type: text/plain; charset="UTF-8";',
            'From: ' . $from,
            'Reply-To: ' . $from,
            'Return-Path: ' . $from,
        );

        mail($sendTo, $subject, $emailText, implode("\n", $headers));

        $responseArray = array('type' => 'success', 'message' => $okMessage);
    }
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
else {
    echo $responseArray['message'];
}

Here is what I would like to achieve:

In the line

$from = 'Demo contact form <info@email.com>';

I would like to get the sender email displayed which should be taken from the email form field.

 

 

In the line

$subject = 'Data Form: ';

I would like to get the sender's full name displayed which should be taken from full name form field.


In the line

$emailText = "You have new message from contact form\n=============================\n";

I would like to have all the data displayed, but I would like to add them some basic HTML styling so they are not sent as a plain text. 
 

If possible, I would also like to get the sender's IP included at the end of the message.


Is anyone here kind enough, to help me get things done? Thanks!  :-*  :birthday: 


 


Edited by SophieR, 12 May 2017 - 06:00 AM.


#2 Jacques1

Jacques1
  • Members
  • PipPipPip
  • Turtles all the way down
  • 4,224 posts

Posted 12 May 2017 - 09:24 AM

I suggest you read an introduction to PHP. This will save you a lot of trouble in the future and make you less dependent on random people on the Internet. Form processing is very, very basic stuff, and I'm sure you can figure it out yourself in a few minutes. If you run into actual problems, feel free to come back.

 

Using the member's e-mail address as the From address is not a good idea, because this is considered forgery and can get your e-mails marked as spam. The e-mail comes from your server, not the member's server. You can put the member's address into the Reply-To header.

 

And the usual disclaimer: The mail() function requires a deep understanding of the SMTP protocol, otherwise you'll quickly end up with vulnerabilties. If you're less experienced, you should use a library like PHPMailer which takes care of the ugly details for you.



#3 SophieR

SophieR
  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 12 May 2017 - 10:29 AM

Hi Jacques1,

Thank you for expressing your concerns and suggestions. You can believe me that I have been spent more than just a few minutes trying to figure out how these "basic things"  work, but no matter what I try, I can't get it done. I'm planning to learn some PHP stuff in the future, but currently I have no time to do it. It was my last resort to come into the forums and ask people if they can help me out... 

I will however use your advice and put the From address into the Reply-to field. 

 

If this is really such a basic stuff, I'm pretty sure the guru's of the PHP will be able to help me and other users waiting patiently for the new website, in no time. We thank you all in advance!  ;D



#4 Jacques1

Jacques1
  • Members
  • PipPipPip
  • Turtles all the way down
  • 4,224 posts

Posted 12 May 2017 - 10:35 AM

Help you with what? If you've spent more than a few minutes with PHP, then you surely know the $_POST variable and how to access the form field values within it. So where exactly is the problem?

 

If you expect us to write the code for you, that won't happen. This is a help forum, not a we-do-your-work forum.



#5 SophieR

SophieR
  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 13 May 2017 - 09:16 AM

Tried to do some "simple" things since yesterday and the code still does not work... Any suggestions, please? 

 

<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');
 
// configure
$from = $_POST['name'] . '<izjava@email.com>';
$reply = $_POST['email'];
$sendTo = 'Demo contact form <info@email.com>';
$subject = 'Electronic contact form: ' . $_POST['name'];
// variable names - text to appear in the email
$name = $_POST['name'];
$birthday = $_POST['birthday'];
$house = $_POST['house_adress'];
$postnr = $_POST['post_adress'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$nickname = $_POST['nickname'];
$shirt = $_POST['shirt'];
$sticker = $_POST['sticker'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
$okMessage = 'Your data hes been sent.';
$errorMessage = 'There was an error. Try again later.';
$recaptchaSecret = 'xxx-xxxxxxxxxx_xxxxxxxxx_xxxxxxxxxxxxxx';
 
// let's do the sending
 
try
{
    if (!empty($_POST)) {
 
        // validate the ReCaptcha, if something is wrong, we throw an Exception, 
        // i.e. code stops executing and goes to catch() block
         
        if (!isset($_POST['g-recaptcha-response'])) {
            throw new \Exception('ReCaptcha is not set.');
        }
 
        // do not forget to enter your secret key in the config above 
        // from https://www.google.com/recaptcha/admin
         
        $recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
         
        // we validate the ReCaptcha field together with the user's IP address
         
        $response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
 
 
        if (!$response->isSuccess()) {
            throw new \Exception('ReCaptcha was not validated.');
        }
         
        // everything went well, we can compose the message, as usually
         
        $emailText = '<html>
            <body>
                <p style="padding:10px;font-weight:bold">Electronic membership form:</p> \n
                <p style="padding:5px;background-color:#ddd">Full name: <strong>'$name'</strong></p> \n
                <p style="padding:5px;">Date of birth: <strong>'$birthday'</strong></p> \n
                <p style="padding:5px;background-color:#ddd">street address: <strong>'$house'</strong></p> \n
                <p style="padding:5px;">Post address: <strong>'$postnr'</strong></p> \n
                <p style="padding:5px;background-color:#ddd">Email: <strong>'$email'</strong></p> \n
                <p style="padding:5px;">Phone number: <strong>'$phone'</strong></p> \n
                <p style="padding:5px;background-color:#ddd">Nickname: <strong>'$nickname'</strong></p> \n
                <p style="padding:5px;">T-shirt size: <strong>'$shirt'</strong></p> \n
                <p style="padding:5px;background-color:#ddd">Sticker color: <strong>'$sticker'</strong></p> \n
                <br/>
                <hr/>
                <p style="padding: 10px;">sender's IP number: <strong>'$ipAddress'</strong></p>
            </body>
        </html>'
 
        $headers = array('Content-Type: text/html; charset="UTF-8";',
            'From: ' . $from,
            'Reply-To: ' . $reply,
            'Return-Path: ' . $from,
        );
 
        mail($sendTo, $subject, $emailText, implode("\n", $headers));
 
        $responseArray = array('type' => 'success', 'message' => $okMessage);
    }
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
 
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);
 
    header('Content-Type: application/json');
 
    echo $encoded;
}
else {
    echo $responseArray['message'];
}


#6 Jacques1

Jacques1
  • Members
  • PipPipPip
  • Turtles all the way down
  • 4,224 posts

Posted 13 May 2017 - 10:14 AM

How does it “not work”?

 

There are syntax problems in the $emailText string, because you've written constant strings and variables next to each other instead of correctly concatenating them:

' A string '.$variable.' another string '    // note the "." operator

Inserting user-controlled variables into HTML documents is generally a bad idea, because attackers can use this to inject malicious content (e. g. JavaScript code). It's also possible that you screw up your own document due to special characters. You need to escape dynamic input:

/**
 * Applies HTML-escaping to a string, so that it can safely be used in simple HTML contexts
 *
 * @param string $raw      the input
 * @param string $encoding the character encoding of the input, e. g. 'UTF-8'
 *
 * @return string the escaped input
 */
function html_escape($raw, $encoding)
{
    return htmlspecialchars($raw, ENT_QUOTES | ENT_SUBSTITUTE, $encoding);
}
const EMAIL_CHAR_ENCODING = 'UTF-8';



// note the escaped variables
$emailText = '
    <html>
        <body>
            <p style="padding:10px;font-weight:bold">Electronic membership form:</p>
            <p style="padding:5px;background-color:#ddd">Full name: <strong>'.html_escape($name, EMAIL_CHAR_ENCODING).'</strong></p>';
// etc.

You also cannot have character sequences like \n in a single-quoted string. Either remove them (what's the point anyway?) or make the string double-quoted (which means all attributes have to be single-quoted or escaped with a backslash).

 

There are cleverer and cleaner ways of generating HTML mails, but that's another story.






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users