Need a secure PHP contact form, or a captcha

Recently my server was hacked via SQL injection. Could it possibly have been through my contact form? i have been receiving many submissions with jumbled text as the comment line.
My code is below.

If the answer is yes, I think it is about time to add a captcha. Any suggestions on the best route to go? I tried implementing reCaptcha by google, but it wasn’t working correctly.

$email = Trim(stripslashes($_POST['email']));
$EmailTo = "(removed)";
$Subject = " - Comment/Question";
$name = Trim(stripslashes($_POST['name']));
$message = Trim(stripslashes($_POST['message']));

// validation
if (Trim($email)=="") $validationOK=false;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";

// prepare email body text
$Body = "";
$Body .= "name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "\n";
$Body .= "message: ";
$Body .= $message;
$Body .= "\n";

// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$email>");

// redirect to success page
if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=success.htm\">";
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";

Thanks ahead of time!

A captcha is not going to prevent the hacking it is more to stop automatic submission.

It looks like your form could do with better validation anyway even if it is not the problem. There are a lot of ready made forms you could look at or write your own. php now has some data filtering functions which may help:

1 Like

Unless there’s some code missing, I can’t see anywhere your example talks to the database, so it’s hard to see whether anything could be improved there. If you’re still using the older mysql functions (as opposed to mysqli or PDO) that can make things harder then they perhaps need to be.

These statements could certainly have the validation improved - they will currently allow a lot of junk through.

1 Like

@noslenwerd What you might have been a victim of was Email injection if this was the script that caused the issue since like @droopsnoot mentioned, there isn’t any SQL in here.

Email injection: (not a thorough guide, but explains how it works)

Ways to handle it: (honeypot strategy + time-based protection sounds like a really good idea)

One of the biggest web application security principles is to never trust user data. Always act as if it’s malicious. So that means filter and validate data in from your user and escape the data out (preventing XSS).

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.