Is This Contact Form Email Script Secure - javascript

I found the following contact form script online and I want to find out if it is secure, and if it is not how I might make it more secure. I just went back to the page where I think I got the code a long time ago and I see one commentor said :
"client side validation is only for user conveneicne, it doens't prevent spam, hackers, or annoying web devs. All a hacker has to do is create their own HTML file without javascript. Spam bots wouldn't even use the form they'll just parse it for the id's and send raw packets. Always check input on the server, never trust the user. "
I'm not exactly sure what that means, but hoping if someone sees a vulnerability in the code below it the comment may make more sense :
<?php
$EmailFrom = Trim(stripslashes($_POST['Email']));
$EmailTo = "info#mysite.com";
$Subject = "Customer Inquiry from MySite.com";
$Name = Trim(stripslashes($_POST['Name']));
$Tel = Trim(stripslashes($_POST['Tel']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=http://www.mysite.com/contact-us-error.php\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Tel: ";
$Body .= $Tel;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=http://www.mysite.com/contact-us-success.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=http://www.mysite.com/contact-us-error.php\">";
}
?>
Thanks for taking a look

You need to understand why some things aren't secure, not just ask people when you don't know.
First of all, you mentioned client-side validation. Are there any constraints you're trying to validate client-side? For instance, is there javascript (or maybe an HTML attribute) that prevents the user from typing more than a certain number of characters in the body of the email?
If so, and if you count this as a security breach, then the page is not secure. If I wanted to abuse your site in this way, I couldn't do it just by visiting the site in the normal way with a browser. But that doesn't stop me from sending whatever I want over the network. I could use something like curl ( http://curl.haxx.se/ ) to send a long request to your server; your server would have no way of knowing it wasn't from a browser, wouldn't check its length, and would send the email.
There's another way an attacker can use the server for something it's clearly not intended for. Namely, they can add extra headers. For instance, suppose they wanted to add the header MyHeader: something malicious. They could send a request in which $_POST['Email'] was the following string:
me#example.com>\r\nMyHeader: something malicious\r\nJunkHeader: junk
Then, the string "From: <$EmailFrom>" would look like this:
From: <me#example.com>
MyHeader: something malicious
JunkHeader: junk>
And those are the headers that would be sent. (I added a line of junk so that the extra > at the end wouldn't appear as part of MyHeader interfere with whatever nefarious plan I was attempting.)
Presumably because of this vulnerability, according to http://uk1.php.net/manual/en/function.mail.php : "The additional_parameters parameter is disabled in safe_mode and the mail() function will expose a warning message and return FALSE when used." (From PHP4.2.3 onwards.)
To fix this, I suppose it is sufficient to check that $EmailFrom contains no newline characters, and refuse to send the email if it does.

Related

What is wrong with my form.php (reCaptcha) [duplicate]

My previous question on StackOverflow was about that someone was sending me hundreds of spam emails every few hours. Now, I fixed the script on the server side but the next morning I still got 30 emails or something and my hosting company gave me a new password to my FTP and moved my index files to a backup map(website offline), they said it was hacked because of the suspicious script below. They said "This often happens via a leaked script in your website, a script that is "out of date". What does that mean? They say in the email that there is something with this script file. Which is impossible to hack in right because I used reCaptcha on the server side, is there something missing?
<?php
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
/* OUTCOMMENTED CODE BELOW DOESN'T LET FORM SEND IF EVERYTHING IS CHECKED????
if(!$captcha){
echo '<h2>Check captcha .</h2>';
exit;
}*/
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=(SECRETKEY)&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo '<span id="status" style="font-size:1vmax;color:red;">ReCaptcha ERROR</span>';
}else
{
if( isset($_POST['n']) && isset($_POST['e']) && isset($_POST['mn']) &&
isset($_POST['m']) ){
$n = $_POST['n']; // HINT: use preg_replace() to filter the data
$e = $_POST['e'];
$mn = $_POST['mn'];
$m = nl2br($_POST['m']);
$to = "gesternl#gester.nl";
$from = $e;
$subject = 'Contact Formulier-eng';
$message = '<b>Naam:</b> '.$n.' <br><b>Email:</b> '.$e.' <br><b>Mobiel-nummer:</b> '.$mn.' <p>'.$m.'</p>';
$headers = "Van: $from\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
if( mail($to, $subject, $message, $headers) ){
echo "success";
} else {
echo "The server failed to send a message. Please try again later. Thank you!";
}
}
}
?>
I just uploaded it again to see what is going to happen now. Can someone please help me make this file secure for a hacker. Nobody really helped in the previous question but only gave advice without code (and I am nooby).
(The outcommented code around line 8 doesn't work which i don't understand, does someone know why is that why someone can hack into it maybe?)
And yes the code in the HTML for recaptcha is well linked with the public key
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=(SECRETKEY)&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
This fragment of code is an unfortunate bit of nonsense that has found its way into a lot of (terrible) tutorials. It provides no protection whatsoever -- the condition is always false, because $response.success is interpreted as concatenating the constant success to the API response returned by the reCaptcha API. This will cause the CAPTCHA to be always treated as valid, regardless of the user's input.
Use the Google reCaptcha library to verify responses from the reCaptcha API. It is available at: https://github.com/google/recaptcha
You're not sanitizing user input, for one. You should fix that right away as it's a security flaw.
You've to sanitizing user input as said #kevin Cai
You've an error in line: if($response.success==false)
$response=file_get_contents("......");
$result = json_decode($response);
if($result->success==false){

Contact form and PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm new to dev, just learning it as we speak. I've yet to learn PHP and JavaScript/JQuery so I'm having trouble with my contact form on my site.
The JavaScript seems to be working, but the PHP action isn't. It's open script I've pulled from the web, so I'm sure the actions are missing some code and since I have no idea what I'm looking at, I'm completely lost. Any help would be amazing.
<!-- FORM -->
<form id="form" form role="form" action="contact_form.php" method="post">
<p id="returnmessage"></p>
<br/>
<label>Name: <span>*</span></label>
<br/>
<input type="text" id="name" placeholder="Name"/><br/>
<br/>
<label>Email: <span>*</span></label>
<br/>
<input type="text" id="email" placeholder="Email"/><br/>
<br/>
<textarea id="message" placeholder="Message......."></textarea><br/>
<br/>
<input type="button" id="submit" value="Send"/>
<br/>
</form>
PHP
<?php
//Fetching Values from URL
$name = $_POST['name1'];
$email = $_POST['email1'];
$message = $_POST['message1'];
$contact = $_POST['contact1'];
//sanitizing email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
//After sanitization Validation is performed
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (!preg_match("/^[0-9]{10}$/", $contact)) {
echo "<span>* Please Fill Valid Contact No. *</span>";
} else {
$subject = $name;
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From:' . $email. "\r\n"; // Sender's Email
$headers .= 'Cc:' . $email. "\r\n"; // Carbon copy to Sender
$template = '<div style="padding:50px; color:white;">Hello ' . $name . ',<br/>'
. '<br/>Thank you...! For Contacting Us.<br/><br/>'
. 'Name:' . $name . '<br/>'
. 'Email:' . $email . '<br/>'
. 'Contact No:' . $contact . '<br/>'
. 'Message:' . $message . '<br/><br/>'
. 'This is a Contact Confirmation mail.'
. '<br/>'
. 'We Will contact You as soon as possible .</div>';
$sendmessage = "<div style=\"background-color:#7E7E7E; color:white;\">" . $template . "</div>";
// message lines should not exceed 70 characters (PHP rule), so wrap it
$sendmessage = wordwrap($sendmessage, 70);
// Send mail by PHP Mail Function
mail(ash.cruikshank#gmail.com, $subject, $sendmessage, $headers);
echo "Your Query has been received, We will contact you soon.";
}
} else {
echo "<span>* invalid email *</span>";
}
JAVASCRIPT
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var contact = $("#contact").val();
$("#returnmessage").empty(); //To empty previous error/success message.
//checking for blank fields
if(name==''||email==''||contact=='')
{
alert("Please Fill Required Fields");
}
else{
// Returns successful data submission message when the entered information is stored in database.
$.post("contact_form.php",{ name1: name, email1: email, message1:message, contact1: contact},
function(data) {
$("#returnmessage").append(data);//Append returned message to message paragraph
if(data=="Your Query has been received, We will contact you soon."){
$("#form")[0].reset();//To reset form fields on success
}
});
}
});
});
Your first problem is that you are not naming any of your variables from your html form. PHP needs these to be able to process the information. For instance:
<input type="text" id="name" placeholder="Name"/>
Needs to have a name field (not just the id, type, and placeholder). Here is how it should look to match the post variables in your PHP script:
<input type="text" id="name" name="name1" placeholder="Name"/>
You should do this with the rest of the HTML inputs as well. Make sure they match the variable in the POST in the php form (that's the one that is called $_POST[''] in the PHP script) This will solve your first problem.
Also, as is mentioned in the comments, especially when developing your code, it's a very good idea to put error reporting in the top of your code to catch any problems. You can get some very information errors if you put this at the top of your code:
<?php error_reporting(E_ALL); ini_set('display_errors', 1); ?>
Note, it's also probably a good idea to save the email address in a variable, rather than hard-coding it.
As for the sendmessage variable, you will need to concatenate the variables like this (as is mentioned above in the comments), otherwise the second $sendmessage variable will overwrite the second one. (note the . just before the = on the second row)
$sendmessage = "<div style=\"background-color:#7E7E7E; color:white;\">" . $template . "</div>";
$sendmessage .= wordwrap($sendmessage, 70);
However, you might want to clean it up a little just to make sure it works. Before you star trying to concatenate two items into one variable try something like this as a plain text message in just one variable. It should send through fine, and then you can worry about the formatting later once you understand how it works.
I recommend reading up on some tutorials as well (http://w3schools.com is pretty good for learning), but this sort of thing you are doing is a good place to start. If you run into more troubles, try stripping down the code to its bare minimum (e.g. remove the HTML segments from the email; just send it as plain text first to make sure that is working and after that put it back in, remove the regex check, and the javascript until you have the form working, and then bit by bit adding the pieces back in. This way you'll get a better understanding how the pieces work).
Change
$name = $_POST['name1'];
$email = $_POST['email1'];
$message = $_POST['message1'];
$contact = $_POST['contact1'];
to
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$contact = $_POST['contact'];
And give name attribute (name="name", name="email" ..)to each inputs.
It will be work.

How to process HTML forms?

I have made an HTML form. It is a sort of a research form and generate scores based on the values entered through some formulae. After I have done with calculating scores, I want to send the scores via an email. Should I use PHP or JavaScript to do that?
thank you
PHP provides a convenient way to send email with the mail() function.
Syntax
mail(to,subject,message,headers,parameters)
Example :
<?php
$to = aa#bbb.com;
$subject = 'results';
$message = 'message ';
$headers = 'From: your_email#xxx.com';
mail($to, $subject, $message, $headers);
?>
You can learn this concept here
You can see examples here
Post your form to a PHP script and you can read the form fields using the $_POST variable. Make sure your form has name="xxx" fields. These will be your $_POST['xxx'] array index names.
You can do the calculations in Javascript,in browser, in clients side.
But sending emails.... you do this via PHP, on the server side.
An example of a PHP script sending the email, as follows
See how I get form field values using $_POST array they come in?
You can build a looong email using lots of variables, just add them to the message.
<?php
$to = $_POST['email'];
$subject = 'Your results';
$message = 'Hello, this is your score email.<br>';
$message.= 'Your result is: '.$_POST['score'];
$headers = 'From: your#email.com';
mail($to, $subject, $message, $headers);

allow only emails from specific domain/subdomain to register and send verification email [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Can someone show me how to allow only emails from specific domain/subdomain to submit email in a form. After submission I would like the email to be sent both to the user's email and my own email. I'm not really sure how to integrate it, so that's mostly what I need help with.
To set up a form that will only accept email addresses with certain domains, you can do two things.
The first is to use the HTML5 input type="email" attribute, which can be used to make sure that any browser that supports HTML5 can validate the email to at least be a valid one.
HTML file:
<form id="contact-form">
<!-- Other inputs here -->
<input name="user-email" type="email" id="user-email" placeholder="johnny.appleseed#gmail.com" required>
<!-- make sure this name="" attribute matches what you ask for in the PHP -->
<button type="submit" id="form-submit">Submit!</button>
</form>
Then you can also use JavaScript to check the domain. Once you know that the email is valid and fits your constraints, you will need to set up an AJAX POST that will send data to the server to handle sending the email. This part can be done like so:
JavaScript file:
$('#form-submit').on('click', function(e) {
e.preventDefault(); // prevent the button from refreshing the page
var userEmail = $('#user-email');
if (userEmail.val().indexOf('.com') !== -1) { // validation
// xyz has .com in it
} else if (userEmail.val().indexOf('.org') !== -1) { // validation
// xyz has .org in it
} else {
$('#submission-info').text('Whoops, we don't send emails, to anything other than .org or .com, please enter a different email and try again.');
}
// this doesn't mean .com or .org is at the end
// you may want to check that by using a regular expression if necessary
var formData = $('#contact-form').serialize(); // This gets the <form id="contact-form"> element's values and serializes it into a string.
$.ajax({
url: 'mail.php', // make sure this file is either in the same directory or the path is changed
type: 'POST',
data: formData
}).done(function(response) {
// do stuff to to show the user that the form was submitted
$('#submission-info').text('Success, your information has been sent to us (and the NSA of course) and we will reply to you as soon as possible.');
}).fail(function(response, error) {
// tell the user what happened that caused the form submission to fail
$('#submission-info').text('Oh no, something happened. Maybe try again');
});
});
For more info about serializing, check out jQuery's API page.
Then in mail.php, you can handle it in PHP by doing something like this:
<?php
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];
$email = $_POST['email'];
$comment = $_POST['comment'];
$formcontent = "From: $firstname $lastname \n Email address: $email \n Message: $message";
$recipient = "john.doe#gmail.com"; // your email goes here instead
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
?>
If you use something like PHPMailer, then you can do all kinds of stuff and it is somewhat more intuitive and clearer and offers many more options that you can configure.
Using PHPMailer would look something like this for a mail.php file:
<?php
require_once("class.phpmailer.php"); // this path should also be set up properly
if ($_POST) { // If something was sent by submitting the form.
$name = htmlspecialchars($_POST["user-name"]);
$email = htmlspecialchars($_POST["user-email"]);
$message = htmlspecialchars($_POST["comment"]);
$subject = "Contact form";
$to = "john.doe#gmail.com"; // your email here
$userBcc = $_POST["user-bcc"]; // You can BCC the user's email
$mail = new PHPMailer();
$mail->From = "xyz#xyzs.com"; // make sure to change this to something else
$mail->FromName = "XYZ XYZ"; // change this too.
$mail->AddReplyTo($email, $name);
if($userBcc == true) {
$mail->addBCC($email);
}
$mail->Subject = $subject;
$mail->Body = $message;
if(!$mail->Send()) {
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
}
?>
So now you should have a form that works. I would suggest testing it a little bit by just sending emails to yourself and doing test submissions before you make it live. You may also want to implement some form of anti-spam, depending on the audience using the site. Forgive me if I forget anything or it isn't clear, I will edit the post and try to detail/fix anything I can.
Good luck and let me know how it goes!

Sending an uploaded file through email without saving it first

I am creating an application that allows a user to attach a file, type a message, then an email is sent using the PHP mailer plugin for wordpress. I use javascript to get the file information from the upload html form and then php to send the email. The plugin works when sending a file that is saved on the server in a specific location using this function:
$mail->AddAttachment("./new6.txt","attachment");
I was wondering if there is a way to email the file selected without having to save it to the server. In other words, can a user select a file to upload, but send the file with this php function without saving it in a location to be retrieved? I know there is a $_FILES array that you can get the file's information but will that file be able to be sent without it being saved somewhere first? I'm guessing not since the whole point of the upload form is to "upload" it but just wondering if something could be done in javascript or something.
Thanks for any help
You can't truly do that, but you could do this to get a close effect:
$filename = $_FILES['file_name']['tmp_name'];
$main->AddAttachment($filename, "attachment");
// Send the email... then:
unset($filename);
This adds the file as an attachment, sends the email, then deletes the file. The uploaded files in the $_FILES array will automatically be flushed out eventually, so I'm not sure if the unset() part even does anything significant, but it surely gets rid of the file.
Without Saving file in Server, you can not attach it for mail.
1> Mailing function is executing in Server.
2> It is not possible from Server to get the absolute file path in client machine as in web, the client machines do not have any absolute address.
3> So the file is needed to be uploaded in server to get a real path for the file to have in attachment of Mail.
I know this is a rather old question, but I think there's a rather useful answer that was never given. For the sake of those like me who happned along this question while searching for an answer to this question or similar, here you go.
When you upload a file to a server from a form, it's saved to the tmp directory automatically. Technically it's impossible to do anything with a form uploaded file without saving, because it's done for you automatically. However, because tmp is automatically cleaned on every reboot, this shouldn't be an issue in terms of building up too much backlog, if you either reboot often or set up a cron to delete your tmp directories contents regularly.
However, because it's saved to tmp, and because you can manipulate the file from there, it is possible to send the file without saving it for any form of longevity, and without actually writting anything to save it. Provided you perform all the necessary security checks on the file (verifying the contents, MIME-type and such that I won't go into now, but you can read up on how to do here), you can use the following php function which I got from Codexworld and modified to use the tmp files. All you need to do is pass
the parameters, and the $files is an array of files you've hopefully already vetted.
function multi_attach_mail($to, $subject, $message, $senderEmail, $senderName, $files = array()){
$from = $senderName." <".$senderEmail.">";
$headers = "From: $from";
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// Preparing attachment
if(!empty($files)){
for($i=0; $i<count($files); $i++){
if(is_file($files[$i]["tmp_name"])){
$tmp_name = basename($files[$i]["tmp_name"]);
$file_name = $files[$i]["name"];
$file_size = filesize($files[$i]["tmp_name"]);
$message .= "--{$mime_boundary}\n";
$fp = fopen($files[$i]["tmp_name"], "rb");
$data = fread($fp, $file_size);
fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".$file_name."\"\n" .
"Content-Description: ".$file_name."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".$file_name."\"; size=".$file_size.";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
}
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $senderEmail;
// Send email
$mail = mail($to, $subject, $message, $headers, $returnpath);
// Return true, if email sent, otherwise return false
if($mail){
return true;
}else{
return false;
}
}

Categories

Resources