Skip to content

Instantly share code, notes, and snippets.

@patotoma
Last active October 7, 2023 07:39
Show Gist options
  • Star 41 You must be signed in to star a gist
  • Fork 20 You must be signed in to fork a gist
  • Save patotoma/8860726 to your computer and use it in GitHub Desktop.
Save patotoma/8860726 to your computer and use it in GitHub Desktop.
secure php contact form
<!DOCTYPE html>
<?php error_reporting(0); ?>
<html lang="en">
<head>
<title>Secure contact form</title>
<meta charset="utf-8">
<style>
p {
margin: 0;
color: red;
}
</style>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$name = htmlspecialchars(stripslashes(trim($_POST['name'])));
$subject = htmlspecialchars(stripslashes(trim($_POST['subject'])));
$email = htmlspecialchars(stripslashes(trim($_POST['email'])));
$message = htmlspecialchars(stripslashes(trim($_POST['message'])));
if(!preg_match("/^[A-Za-z .'-]+$/", $name)){
$name_error = 'Invalid name';
}
if(!preg_match("/^[A-Za-z .'-]+$/", $subject)){
$subject_error = 'Invalid subject';
}
if(!preg_match("/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/", $email)){
$email_error = 'Invalid email';
}
if(strlen($message) === 0){
$message_error = 'Your message should not be empty';
}
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<label for="name">Name:</label><br>
<input type="text" name="name">
<p><?php if(isset($name_error)) echo $name_error; ?></p>
<label for="subject">Subject:</label><br>
<input type="text" name="subject">
<p><?php if(isset($subject_error)) echo $subject_error; ?></p>
<label for="email">Email:</label><br>
<input type="text" name="email">
<p><?php if(isset($email_error)) echo $email_error; ?></p>
<label for="message">Message:</label><br>
<textarea name="message"></textarea>
<p><?php if(isset($message_error)) echo $message_error; ?></p>
<input type="submit" name="submit" value="Submit">
<?php
if(isset($_POST['submit']) && !isset($name_error) && !isset($subject_error) && !isset($email_error) && !isset($message_error)){
$to = 'youremail@addres.com'; // edit here
$body = " Name: $name\n E-mail: $email\n Message:\n $message";
if(mail($to, $subject, $body)){
echo '<p style="color: green">Message sent</p>';
}else{
echo '<p>Error occurred, please try again later</p>';
}
}
?>
</form>
</body>
</html>

Secured PHP Contact Form

<?php
  if(isset($_POST['submit'])){
    $name = htmlspecialchars(stripslashes(trim($_POST['name'])));
    $subject = htmlspecialchars(stripslashes(trim($_POST['subject'])));
    $email = htmlspecialchars(stripslashes(trim($_POST['email'])));
    $message = htmlspecialchars(stripslashes(trim($_POST['message'])));
    if(!preg_match("/^[A-Za-z .'-]+$/", $name)){
      $name_error = 'Invalid name';
    }
    if(!preg_match("/^[A-Za-z .'-]+$/", $subject)){
      $subject_error = 'Invalid subject';
    }
    if(!preg_match("/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/", $email)){
      $email_error = 'Invalid email';
    }
    if(strlen($message) === 0){
      $message_error = 'Your message should not be empty';
    }
  }
?>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
  <label for="name">Name:</label><br>
  <input type="text" name="name">
  <p><?php if(isset($name_error)) echo $name_error; ?></p>
  <label for="subject">Subject:</label><br>
  <input type="text" name="subject">
  <p><?php if(isset($subject_error)) echo $subject_error; ?></p>
  <label for="email">Email:</label><br>
  <input type="text" name="email">
  <p><?php if(isset($email_error)) echo $email_error; ?></p>
  <label for="message">Message:</label><br>
  <textarea name="message"></textarea>
  <p><?php if(isset($message_error)) echo $message_error; ?></p>
  <input type="submit" name="submit" value="Submit">
  <?php 
    if(isset($_POST['submit']) && !isset($name_error) && !isset($subject_error) && !isset($email_error) && !isset($message_error)){
      $to = 'youremail@addres.com'; // edit here
      $body = " Name: $name\n E-mail: $email\n Message:\n $message";
      if(mail($to, $subject, $body)){
        echo '<p style="color: green">Message sent</p>';
      }else{
        echo '<p>Error occurred, please try again later</p>';
      }
    }
  ?>
</form>

How to use:

  • Download contact.php file or just copy the code above to your *.php file.
  • Put the file to your website directory.
  • Change: $to = 'youremail@addres.com'; to your email address.

Feel free to modify code to suit your needs.

If you have any questions or innovations please leave me a comment.

patriktoma.studenthosting.sk

@ntot
Copy link

ntot commented Apr 10, 2017

Hello, amazing and well written script. Just one question, how can I redirect people to a new page when they successfully submit the page? When I see the success message, if I refresh the page it sends me the same details again. Thank you for the good work.

Peter

@patotoma
Copy link
Author

hello @ntot,

for redirecting you can either use php header function

or just redirect using javascript like this:

echo '<script>window.location = "http://www.google.com/";</script>';

@ntot
Copy link

ntot commented Apr 10, 2017

Thank you, so just to confirm since I am not a PHP expert... Would it be:

    <?php 
        if(isset($_POST['submit']) && !isset($name_error) && !isset($subject_error) && !isset($email_error) && !isset($message_error)){
          $to = 'youremail@addres.com'; // edit here
          $body = " Name: $name\n E-mail: $email\n Message:\n $message";
          if(mail($to, $subject, $body)){
            echo 'header('Location: http://www.example.com/');';
          }else{
            echo '<p>Error occurred, please try again later</p>';
          }
        }
      ?>

@patotoma
Copy link
Author

@ntot not quite like that, you don't want to use echo for such things. Echo is for printing content out so it can be read by the clients browser. Header is a php function so there is no point in printing it out. What you want to do is something like this:

if(mail($to, $subject, $body)){
    header('Location: http://www.example.com/');
}

Example with using echo would be printing out some javascript code so it can be interpreted by the clients browser:

if(mail($to, $subject, $body)){
    echo '<script>window.location = "http://www.google.com/";</script>';
}

@ntot
Copy link

ntot commented Apr 12, 2017

Thank you for getting back to me @patotoma, I tried the header location as you said but get the: cannot modify header information, header already sent error, any ideas? Also the JS solution is good however if you press the back button the details from the form are still there so you can spam the form.

@patotoma
Copy link
Author

@ntot take a look at this in order to fix the cannot modify header information error. Also that thing with the form when you press back button the form is re-submitted, that's normal browser behaviour, if you need to disable that you need to handle form submitting in some other way and with additional logic.

@lena9393
Copy link

lena9393 commented Jun 9, 2018

Hi, Could you perhaps provide a php code snippet that would need to be added to the contact form if I wanted to attach a file and send together with the email? I would be very grateful.

<label for="image">Image:</label><br> <input type="file" name="image">

@sharonkangas
Copy link

Hi! Thanks so much for sharing this code. I would love to use it on my personal website, but am running into a couple problems. If I save the code as a stand-alone page , it works like a charm. But if I incorporate it into my one-page scrolling website, it no longer works. Specifically, it (1) provides no error messages for invalid entries, and (2) then after submitting, instead of the "message sent" message and an email in my inbox, it tries to redirect me to a non-existent webpage: www....com/<?php%20echo%20htmlspecialchars($_SERVER[
I can share my index.html file if you'd like to have a look. Thanks in advance for any insight you can share.

@sharonkangas
Copy link

I actually seem to have solved the problem myself. I didn't realize until minutes ago that any page with php code had to use the .php file extension. I made that change and now it works! Thanks again!

Copy link

ghost commented Sep 26, 2018

Your form isn't sending emails to the email addresses like xxx@domain i.e., business emails.

@adriandhart
Copy link

adriandhart commented Nov 13, 2018

Thanks for sharing this. I have a suggestion though. Purely for tidier code; you can eliminate the empty paragraph tags where errors would be displayed, below each input like this...

<?php if(isset($name_error)) echo '<p>' . $name_error . '</p>'; ?>

Thanks again :)

@Hovoaslanian
Copy link

Hi there,

what about if i want only to use PHP code and embed it to my own Template will it work?

@osazeblogger
Copy link

Thanks i love this 100%

@ChloeFrazer
Copy link

Thank you for sharing, it's been the perfect base to build from.

@JanekVerano
Copy link

Hello everybody,

I'm new to GitHub and I have very little experience. Can you tell me how this contact form is secure?
It seems to me, that it requires all fields to be filled out with appropriate data (like an email-address [A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}) but I don't see, how bots should be stopped. Thank you for your assistance!

@BooneDawg
Copy link

I cannot get the email to be delivered to my email address I entered. I checked the email and it is correct.

@lhardt
Copy link

lhardt commented May 11, 2021

Wouldn't it be safer to use <form action="">?

@Shalu-patidar
Copy link

i add another input of phone but it is not display in url

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment