Solved

Secure contact form with phpmailer

Posted on 2011-03-02
10
518 Views
Last Modified: 2012-05-11
Is it possible to make secure contact form that use phpmailer. How I secure it so if I get spam or dangerous exe files in attachment in my mail box?

Here is my send page code:

<?php
error_reporting(E_ALL ^ E_NOTICE);
$message .= "<b>Error ID:</b> {$_POST['error_id']}<br /><br />";
$message .= "<b>Day:</b> {$_POST['day']}<br /><br />";
$subject = "New error-message";

require("class.phpmailer.php");
$mail = new PHPMailer();

$mail->From = "no-reply@mail.be";
$mail->FromName = "Errormessage";
$mail->AddAddress("matti@mail.be");


$mail->AddAttachment($_FILES['tiedosto1']['tmp_name'], basename($_FILES['tiedosto1']['name']));
$mail->AddAttachment($_FILES['tiedosto2']['tmp_name'], basename($_FILES['tiedosto2']['name']));
$mail->AddAttachment($_FILES['tiedosto3']['tmp_name'], basename($_FILES['tiedosto3']['name']));
$mail->AddAttachment($_FILES['tiedosto4']['tmp_name'], basename($_FILES['tiedosto4']['name']));
$mail->AddAttachment($_FILES['tiedosto5']['tmp_name'], basename($_FILES['tiedosto5']['name']));
$mail->IsHTML(True);                              

$mail->Subject  =  $subject; //
$mail->Body     =  $message;
if(!$mail->Send())
{
   echo "Error<p>";
   echo "Mailer Error: " . $mail->ErrorInfo;
   exit;
} else {
}
?>
0
Comment
Question by:mattimeikalainen
  • 3
  • 2
  • 2
  • +3
10 Comments
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 35024717
It would be difficult to write a malware scanner in PHP so you need to make sure your anti-virus on your computer that receives the email is working and protecting you.  You can scan the message text for unwanted content with PHP.
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 35024981
You can also validate those extensions on the client side or server side before you start mail attachment process.
0
 
LVL 4

Expert Comment

by:gizmola
ID: 35025537
The $_FILES['somefile']['type'] for any files will provide you a mimetype sent by the client.  This can be tampered with, but it makes a good barrier, if you don't want to accept .exe's or other types of files based on their extensions.

Combined with a whitelist based on this list http://www.w3schools.com/media/media_mimeref.asp you could simply not attach any files where the type column isn't in your list of acceptable attachment types.
0
 

Author Comment

by:mattimeikalainen
ID: 35025971
Can you write me code examples, I dont know how to do it.
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 35026002
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 3

Expert Comment

by:pius_babbun
ID: 35027917
You can check the file extension as you before attach the files in mailer from $_FILES and restrict the exe files for this case.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 35028137
Add a CAPTCHA test to your form that is used to upload the files.  It will not help you avoid evil attachments from evil people, but it will go a long way toward ensuring that you will not get evil files from evil 'bots.  Here is a simple example.  The first script shows how to call the captcha_image.php script.
<?php // RAY_captcha_in_action.php
error_reporting(E_ALL);

// IF ANYTHING WAS POSTED
if (!empty($_POST))
{
    // TEST THE STRINGS
    if ($_POST["_newMd5"] != md5($_POST["_newCode"]))
    {
        // MIGHT WANT TO MAKE THIS USER-FRIENDLY
        echo 'SECURITY CODE NUMBER DID NOT MATCH';
    }
    else
    {
        echo "SUCCESS!";
    }
}
// END OF PHP - PUT UP THE FORM
?>
<form method="post">
<!-- STYLE THIS TO SUIT YOUR PAGE STYLE -->
Type <img style="display:inline;" src="RAY_captcha_image.php?dt=<?php $x = mt_rand(1000,10000); echo base64_encode($x); ?>" /> here:
<input name="_newCode" type="text"   maxlength="64" size="6" autocomplete="off" />
<input name="_newMd5"  type="hidden" value="<?php echo md5($x); ?>" />
<input type="submit" />
</form>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 35028153
... And this second script is the captcha_image.php script that the first one calls.

You can use reCaptcha if you want to, but I find the images quite difficult to read and a little too much of a nuisance.

HTH, ~Ray
<?php // RAY_captcha_image.php

// GENERATES A PICTURE OF A NUMBER INTO THE BROWSER OUTPUT
error_reporting(E_ALL ^ E_NOTICE);

// DECODE THE INCOMING STRING
$data = base64_decode($_GET['dt']);

// CREATE AN IMAGE RESOURCE - CHOOSE THE SIZE THAT BEST MATCHES YOUR PAGE STYLE
$im = imagecreate(46,13);

// WHITE BACKGROUND
$bg = imagecolorallocate($im, 255,255,255);

// GRAY STRIPES
$gray = imagecolorallocate($im, 188,188,188);

// FIREBRICK TEXT
$text = imagecolorallocate($im, 178,34,34);

// ADD THE NUMBER TO THE IMAGE
imagestring($im,5,4,0,$data,$text);

// WRITE A GRAY STRIPE (OR MORE IF YOU CHOOSE)
imageline($im,4,12,38,0,$gray);

// SEND THE IMAGE INTO THE BROWSER OUTPUT STREAM
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);

Open in new window

0
 
LVL 4

Expert Comment

by:gizmola
ID: 35040362
function checkFileType($fileType) {
  $fileTypes = array('image/png', 
                     'image/jpg', 
					 'image/gif',
					 );
   return (isset($fileType) && in_array($fileType, $fileTypes)) ? true : false;
}

Open in new window


You would use this like so:

if checkFileType($_FILES['tiedosto1']['type'])
	$mail->AddAttachment($_FILES['tiedosto1']['tmp_name'], basename($_FILES['tiedosto1']['name']));

Open in new window


if (checkFileType($_FILES['tiedosto1']['type']))
	$mail->AddAttachment($_FILES['tiedosto1']['tmp_name'], basename($_FILES['tiedosto1']['name']));

Open in new window

0
 
LVL 4

Expert Comment

by:gizmola
ID: 35040371
In the example above, use the 2nd if (checkfileType... example.  I accidently pasted in that first example by mistake.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now