/    Sign up×
Community /Pin to ProfileBookmark

php form question: reply to sender

Hello,

I really don’t know much about php, so I put this together piece by piece. I’m trying to figure out how to reply directly to the sender. So far, if I reply to a question, I end up replying to myself. Can anyone help?

Thanks! Here’s the code:

[code=php]
$name = $_POST[‘name’] ;
$email = $_POST[‘from’] ;
$subject = $_POST[‘subject’] ;

$message = “You have recieved a message from:” .”n”;
$message .= $name . “n”;
$message .= $email . “n”;

$message .= $subject . “n”;
$message .= $general . “n”;
$message .= $prayer . “n”;

$message .= stripslashes($_POST[‘message’]).””;

if (!$email) { //If no email…
echo “Sorry, you forgot to enter your email”; //The error message
die(); //Kills the rest of the script, so it doesn’t display and only the error
}
else { //Else if email entered…
mail( “contact@*********************.com”, “Message for Greater Grace Church”,$message, “From: [email]contact@*********************.com[/email]” );
header( “Location: http://www.*********************.com/thank-you.html” );
}
?>[/code]

to post a comment
PHP

9 Comments(s)

Copy linkTweet thisAlerts:
@NogDogMar 14.2018 — _

If I'm understanding correctly, I think if you add a "Reply-To:" header with the value being the user's email address, you'll be good to go.

You'll want to filter it though, to avoid mail header injection attacks. This would probably be sufficient:
[code=php]
$email = filter_var($_POST['from'], FILTER_SANITIZE_EMAIL);
[/code]

_
Copy linkTweet thisAlerts:
@jeff60sauthorMar 14.2018 — _

If I'm understanding correctly, I think if you add a "Reply-To:" header with the value being the user's email address, you'll be good to go.

You'll want to filter it though, to avoid mail header injection attacks. This would probably be sufficient:
[code=php]
$email = filter_var($_POST['from'], FILTER_SANITIZE_EMAIL);
[/code]

_[/QUOTE]


Thank you so much, yes, I'm trying to set up a "reply-to". Where on my php should I put this? $email = filter_var($_POST['from'], FILTER_SANITIZE_EMAIL);

Thanks!
Copy linkTweet thisAlerts:
@NogDogMar 14.2018 — Thank you so much, yes, I'm trying to set up a "reply-to". Where on my php should I put this? $email = filter_var($_POST['from'], FILTER_SANITIZE_EMAIL);

Thanks![/QUOTE]


The line of code I suggested would replace the 2nd line of code in your original snippet, just modifying how $email is set. Then when you actually send the email, add the additional header:
[code=php]
else { //Else if email entered...
mail(
"contact@*********************.com",
"Message for Greater Grace Church",
$message,
"From: contact@*********************.comrnReply-To: $email"
);
header( "Location: http://www.*********************.com/thank-you.html" );
}
[/code]
Copy linkTweet thisAlerts:
@rootMar 14.2018 — When posting code, please observe the fact that all web forums have some form of BB Code tags like the ones in my signature ?

As for the code...

You should sanitize the inputs or your site will be hacked in a few clicks.

IMHO you need to whitelist the form fields your form accepts, you should have HTML5 form fields and then use a validation in to a safe array (whitelisted) elements that are filtered, then format the email message...

eg.

[B]$email = filter_var( $_POST['from'], FILTER_SANITIZE_EMAIL );[/B] you also have FILTER_SANITIZE has several filters to filter inputs , if the item fails, then false is returned to protect the server from an attempted hack. Also use HTML5 form fields, setting the appropriate attributes is only going to help as you can also specify regular expressions in the HTML attribute so that the form can't be submitted until a field that is required has input, etc.

Your script assumes all went well, nothing checked by the return value from the mail() function. You can then decide to send the user back if the form fails validation or to issue a thank you message when all goes well and does not send a confirmation email to the client about their email.
Copy linkTweet thisAlerts:
@jeff60sauthorMar 14.2018 — When posting code, please observe the fact that all web forums have some form of BB Code tags like the ones in my signature ?

As for the code...

You should sanitize the inputs or your site will be hacked in a few clicks.

IMHO you need to whitelist the form fields your form accepts, you should have HTML5 form fields and then use a validation in to a safe array (whitelisted) elements that are filtered, then format the email message...

eg.

[B]$email = filter_var( $_POST['from'], FILTER_SANITIZE_EMAIL );[/B] you also have FILTER_SANITIZE has several filters to filter inputs , if the item fails, then false is returned to protect the server from an attempted hack. Also use HTML5 form fields, setting the appropriate attributes is only going to help as you can also specify regular expressions in the HTML attribute so that the form can't be submitted until a field that is required has input, etc.

Your script assumes all went well, nothing checked by the return value from the mail() function. You can then decide to send the user back if the form fails validation or to issue a thank you message when all goes well and does not send a confirmation email to the client about their email.[/QUOTE]


I thank you both greatly. It could be that I'm just plain over my head with this stuff.
Copy linkTweet thisAlerts:
@phpBerlinerMar 14.2018 — you just need to check the input (post) data before you do something with it because post data is especially dangerous in a mailer. as an example only:

[CODE]
<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$name = $email = $subject = $message = $nameError = $emailError = $subjectError = $messageError = NULL;

// you could add error handling with input validation or just drop the entire else statement from this area
if (isset($_POST['name'])) { $name = holyWater($_POST['name']); } else { $nameError = 1; }
if (isset($_POST['from'])) { $email = filter_var($_POST['from'], FILTER_SANITIZE_EMAIL); } else { $emailError = 1; }
if (isset($_POST['subject'])) { $subject = holyWater($_POST['subject']); } else { $subjectError = 1; }
if (isset($_POST['message'])) { $message = cleanseMessage($_POST['message']); } else { $messageError = 1; }

// when everything is sanitized and validated, add your email script
$mailname = $name;
$mailsubject = $subject;
$mailfrom = $email;
$mailmessage = $message;

$mailTo = "[email protected]";
$headers = "From: " . $mailFrom;
$txt = "You have received an email from " . $name . "nn" . $message;

mail($mailTo, $subject, $txt, $headers);
header("Location: thankyoupage.php");
exit;

} else {
echo 'invalid request method.';
// echo an error or include a php error file or add a header redirect to an error page
// include 'requesterror.php';
//header("Location: requesterror.php");
exit;
}

function holyWater($s) { //string sanitization of some sort is necessary but this could damage textarea messages
$s = trim($s);
$s = stripslashes($s);
$s = strip_tags($s);
$s = htmlspecialchars($s);
}

function cleanseMessage($s) { //sanitization for textarea messages
$s = strip_tags($s);
$s = htmlspecialchars($s);
}

exit;
?>
[/CODE]


just sanitize the input at minimum. you can always add filtering and error handling.
Copy linkTweet thisAlerts:
@jeff60sauthorMar 15.2018 — you just need to check the input (post) data before you do something with it because post data is especially dangerous in a mailer. as an example only:

[CODE]
<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$name = $email = $subject = $message = $nameError = $emailError = $subjectError = $messageError = NULL;

// you could add error handling with input validation or just drop the entire else statement from this area
if (isset($_POST['name'])) { $name = holyWater($_POST['name']); } else { $nameError = 1; }
if (isset($_POST['from'])) { $email = filter_var($_POST['from'], FILTER_SANITIZE_EMAIL); } else { $emailError = 1; }
if (isset($_POST['subject'])) { $subject = holyWater($_POST['subject']); } else { $subjectError = 1; }
if (isset($_POST['message'])) { $message = cleanseMessage($_POST['message']); } else { $messageError = 1; }

// when everything is sanitized and validated, add your email script
$mailname = $name;
$mailsubject = $subject;
$mailfrom = $email;
$mailmessage = $message;

$mailTo = "[email protected]";
$headers = "From: " . $mailFrom;
$txt = "You have received an email from " . $name . "nn" . $message;

mail($mailTo, $subject, $txt, $headers);
header("Location: thankyoupage.php");
exit;

} else {
echo 'invalid request method.';
// echo an error or include a php error file or add a header redirect to an error page
// include 'requesterror.php';
//header("Location: requesterror.php");
exit;
}

function holyWater($s) { //string sanitization of some sort is necessary but this could damage textarea messages
$s = trim($s);
$s = stripslashes($s);
$s = strip_tags($s);
$s = htmlspecialchars($s);
}

function cleanseMessage($s) { //sanitization for textarea messages
$s = strip_tags($s);
$s = htmlspecialchars($s);
}

exit;
?>
[/CODE]


just sanitize the input at minimum. you can always add filtering and error handling.[/QUOTE]


Thank you so much for this.
Copy linkTweet thisAlerts:
@phpBerlinerMar 15.2018 — the code is not very good but i have no time to write a script for you. The gist of a form processor is listed but it is not the best code for this. For example, i recommend a session with a token to help stop remote form abuse that doesn't provide a token. if you really wish to implement a session, then you could recode the script as follows:

formprocessor.php
[CODE]<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

session_start(); // continue the session from the form page.
//session_regenerate_id(true);
//for tighter security, uncomment the regenerate id line.
//wireless network lag could cause problems with regenerate id, thus storing old id helps. wait before destroy

if (hash_equals($_SESSION['tokenShield'], $_POST['token'])) {
//if the form token matches the session stored token (like server cookie holding the value) then process form
//i prefer a stronger encryption than an md5 with non-cryptographic randomness. I choose SHA-512

//it is a good idea to declare variables and set them before use. also avoids fixation problems.
$name = $email = $subject = $message = $nameError = $emailError = $subjectError = $messageError = NULL;

// you could add error handling with input validation or just drop the entire else statement from this area
if (isset($_POST['name'])) { $name = holyWater($_POST['name']); } else { $nameError = 1; }
if (isset($_POST['from'])) { $email = filter_var($_POST['from'], FILTER_SANITIZE_EMAIL); } else { $emailError = 1; }
if (isset($_POST['subject'])) { $subject = holyWater($_POST['subject']); } else { $subjectError = 1; }
if (isset($_POST['message'])) { $message = cleanseMessage($_POST['message']); } else { $messageError = 1; }

// when everything is sanitized and validated, add your email script
$mailname = $name;
$mailsubject = $subject;
$mailfrom = $email;
$mailmessage = $message;

$mailTo = "[email protected]";
$headers = "From: " . $mailFrom;
$txt = "You have received an email from " . $name . "nn" . $message;

mail($mailTo, $subject, $txt, $headers);
header("Location: thankyoupage.php");
exit;

} else {
//token doesn't match
$_POST = array();
//deleteing cookies here is a good idea too before you destroy session. also unset($_COOKIE['sessionnamegoeshere']; drops the server side cookie.
$_SESSION = array(); session_unset(); session_destroy();
header("Location: securityerror.php");
exit;
}

} else {
echo 'invalid request method.';
// echo an error or include a php error file or add a header redirect to an error page
// include 'requesterror.php';
//header("Location: requesterror.php");
exit;
}

function holyWater($s) { //string sanitization of some sort is necessary but this could damage textarea messages
$s = trim($s);
$s = stripslashes($s);
$s = strip_tags($s);
$s = htmlspecialchars($s);
}

function cleanseMessage($s) { //sanitization for textarea messages
$s = strip_tags($s);
$s = htmlentities($s);
}

exit;
?>
[/CODE]


implement the token on the formpage.php:
[CODE]<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {

session_start();

$salt = "M@ke-a-key(or)Another-Rand0mByt3s-salt";
$makeToken = bin2hex(random_bytes(32)) . $salt;
$finalToken = hash('sha512', $makeToken);

$_SESSION['tokenShield'] = hash_hmac('sha512', $makeToken, $finalToken);

include 'formhtml.php';
exit;

} else {
//error handling for requests other than GET
header("Location: invalidrequest.php");
exit;
}

exit;
?>
[/CODE]


then the form html content (formhtml.php) included in formpage.php:

[CODE]<form method="post" action="formprocessor.php">
<input name="token" value="<?php echo hash_hmac('sha512', $makeToken, $finalToken); ?>" type="hidden" />
<input name="name" type="text" />
<!-- et cetera, et cetera ==>
</form>[/CODE]


then if you place these files outside the root directory, you can load them in the php file with an include statement. For example, if you use xampp for design/development on Windows: make a folder outside the root. Let us call it churchPHP. find the correct path from the webroot to the directory outside of the root.

call form pages from the contact index.php:
[CODE]<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
include dirname(__FILE__) . '/../../churchPHP/formpage.php';
exit;
} else {
header("Location: invalidrequest.php");
exit;
}
?>[/CODE]


now your forms are not accessible by url.

hopefully, you can make sense of this info and implement a better secure form.
Copy linkTweet thisAlerts:
@rootMar 19.2018 — Salting a page only needs an MD5 hash, nothing as complex as a SHA type. The aim is to salt the page so that when the server gets the web form, it will be able to rehash and match that hash in the form.
[code=php]// true or false, is this a web form... with a submit button? Bots don't include submit buttons, they just "push"
$post = ($_SERVER["REQUEST_METHOD"] == "POST") && isset($_POST['submit']) && true;
// whitelist stuff in the form
$whitelist = array(
"name"=>FILTER_SANITIZE_STRING,
"from"=>FILTER_SANITIZE_STRING,
"subject"=>FILTER_SANITIZE_STRING,
"message"=>FILTER_SANITIZE_STRING,
"hash"=>FILTER_SANITIZE_STRING
);

// sanitize
foreach( $whitelist as $key=>&$value)
$value = filter_var( $_POST[ $key ], $value );

// did we pass?
if( !$post or ($whitelist['hash'] != $saltvalue) ) exit;

// headers were a little light
$headers = sprintf("From: %s%sReply-To: %s%sX-Mailer: PHP/%s", $whitelist['from'], PHP_EOL, $whitelist['from'], PHP_EOL, phpversion() );

// format the message section of the email
$emailtxt = sprintf("You have received an email from : %s. %s%s%s", $whitelist['name'], PHP_EOL, PHP_EOL, $whitelist['message']);

// send it and capture any error.
$goto = ( !mail("[email protected]", $whitelist['subject'], $emailtxt, $headers) ) ? "error.php" : "sent.php";
header("Location: {$goto}");
[/code]

*untested likely bugs, you'll just have to work the error messages...

SO as a rough idea, the form presented for processing is tested for a submit button as many bots do not include the submit button, often better to label up as [B]Submit[/B] rather than [B]submit[/B], that way if you have a submit button, how can you really tell if your Submit button is genuinely yours? Well one additional element, a sat hash value in the form should be easily reconstituted and tested for, as well as that, having hidden form elements that are named like Login or Password and are hidden types that are read-only and meant to be received at the server empty, as a human will not see or be able to enter something in to those fields, it is safe to say you can just reject any form you get that has a "Honeypot field" populated when it should be empty. Another trait of bots is that they will stuff any input field it can see in the form with data irrespective of what the parameters for that field is set to.

If you encounter a possible bot, don't give ANY positive feedback like many sites do, it only confirms that they have failed in a hack or login attempt, so just killing the script leave the bot hanging until timeout for a reply. Record the IP address and if you keep on getting multiple login attempts or attempts to post data, your script could be modified to check if the IP address is listed by the system as suspect, Google has a similar system that kicks in if you try to do too many web searches, a bit like that, the system monitors the users IP address and as soon as something happens like data in fields that shouldn't have data, you log the IP and if that happens more than once, you can then just ignore any requests from that IP address for at least 24 hours.

NOTE... you should check with the webhost you use that they have no special requirements for web form and emails, most problems are becaise people do not check their webhost FAQ's on web form email's
×

Success!

Help @jeff60s spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...