Click here to Skip to main content
15,867,141 members
Articles / Web Development

PHP Contact Us Script, Runs Without Modification

Rate me:
Please Sign up or sign in to vote.
4.88/5 (12 votes)
7 May 2021CPOL3 min read 46.1K   957   20   12
PHP contact-us script runs without modification. It detects the domain and emails all the contact-us form-data
Run out of box PHP contact us script, it does not need modification, it will detect the domain and send an email containing the contact message to info@exmple.com whatever fields are in your form; it will detect them and send the form data with email.

Image 1

What is New in PHP Contact Us Script

  • User must enter data in the name field, email, subject, and message before submitting
  • The new version contains more user input filtering. So it keeps the script safe. We sanitize each input key and value using the function htmlspecialchars() and the filter FILTER_SANITIZE_STRING. And I strip any HTML code or invalid characters.

Introduction

Run out-of-box PHP contact-us script, it does not need modification, it will detect the domain and send an email containing the contact message to info@exmple.com whatever fields are in your form; it will detect them and send the form data with email.

System Requirements

  • Any website with hosting supports PHP; Almost all hosts do support it.
  • In other words, you could use it for any website regardless of what it uses: pure HTML/PHP, WordPress, Joomla, Drupal, or any other system

PHP Version

  • PHP 5.6 / PHP 7.0 / PHP 7.1 / PHP 7.2 / PHP 7.3 / PHP 7.4 / PHP 8.0 / PHP 8.1 / PHP 8.2

Background

Lots of contact-us scripts are available over the internet. On the other hand, other scripts need modification of the PHP file before use while this script will run directly out of the box.
So this script is very useful to those who do not know PHP and to beginners of PHP.

Using the Code

  • Unzip the downloaded zip file
  • Then create the contact-us folder in the www directory of your website
  • After that, upload the files to the contact-us folder
  • and that is all.
  • Finally, the contact-us URL is like example.com/contact-us replace example.com with your domain

Modifying contact-us Form Design

  • You could modify the Contact Us page design as you want
  • Add or omit fields as needed
  • Use from_email, from_name, subject, message and captcha as fields names
  • Put your Ads or make your form free of ads
  • You are free to put a link to us or not.

About the contact-us Code

From Action

HTML
<form action="send.php" method="POST">

Fields Names

Use from_email, from_name, subject, message and captcha as main fields' names in your form.

Captcha

If you don’t wish to use a captcha, then change the 1st line of the ‘config.php’ code to be as follows:

PHP
$captcha = false;

If you wish to use a captcha, then no change is needed and the 1st line of the ‘config.php’ code will be as follows:

PHP
$captcha = true;

If you need to modify the form; please note that we use a captcha, include the following in your form:

HTML
<img src="captcha_code_file.php?rand=<?php echo rand(); 
?>" id='captchaimg' ><br>

Enter the code above here : <input id="captcha" 
name="captcha" type="text"><br>

Input Filtering

To keep the script safe, we sanitize each input key and value using FILTER_SANITIZE_STRING. I strip any HTML code or invalid characters.

Thank you URL

Put your own $thank_you_url in the 2nd line of the code.

What Does This Script Do?

  • Check the referrer page and stop the script if it is called directly:
    PHP
    $REFERER = $_SERVER['HTTP_REFERER'];
    if(!preg_match("@^http:\/\/(www\.)?$domain\/@",$REFERER)){
                    die("This page can't be call directly");
    }
  • Validate user email and user name to prevent injecting the wrong command in the header parameter of the mail() function:
    PHP
    if(!$from_email) $from_email = "web_page@$domain";
    if (!filter_var($from_email, FILTER_VALIDATE_EMAIL)) {
                    $Err .= 'Invalid email format<br>';
                    $from_email = "web_page@$domain";
    }
  • Validate the subject and encode it if needed to prevent send failure:
    PHP
    if ($subject && !preg_match('/^[A-Za-z ]+$/',$subject)){
                    $subject = "=?UTF-8?B?".base64_encode($subject)."?=";
    }
  • Store the captcha in session and compare it with the variable
  • Seek all posted variables
    PHP
    foreach ($_POST as $key => $value)
    {
        if ( strpos( strtolower( $key ), 'email' ) !== false ) { 
            $value = filter_var( $value, FILTER_SANITIZE_EMAIL ); 
        } else { 
            $value = filter_var( $value, FILTER_SANITIZE_STRING ); 
        } 
        $value = htmlspecialchars( $value ); 
        $key = filter_var( $key, FILTER_SANITIZE_STRING ); 
        $key = htmlspecialchars( $key ); 
        $message_html .= "<h2>$key</h2><p>$value</p>";
    }
  • Send the message in HTML UTF-8 format to be compatible with most languages
  • Redirect to thank you URL
    PHP
    header('Location: '. $thank_you_url);

PHP Mailing Technique

There are lots of mailing techniques in PHP; PEAR Mail, PHP Mailer, and a mail function. However, we just use the mail function as it is common and simple.

PHP Email Validation

PHP FILTER_SANITIZE_EMAIL Filter

Remove all illegal characters from an email address:

PHP
$from_email = filter_var($from_email, FILTER_SANITIZE_EMAIL);

PHP FILTER_VALIDATE_EMAIL Filter

Check if the variable $email is a valid email address:

PHP
if (!filter_var($from_email, FILTER_VALIDATE_EMAIL)) {                    
    $Err .= 'Invalid email format<br>';               
    $from_email = "web_page@$domain";
}

Validate Email in PHP using a Regular Expression

PHP
$pattern = '/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/';
if(!preg_match($pattern, $from_email)){ 
    $Err .= 'Invalid email format<br>';               
    $from_email = "web_page@$domain";
}

History

  • 14th October, 2016: Initial version
  • 7th May, 2021: Article updated

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Lebanon Lebanon
ASP.Net Hosting on Linux server
---------------------------
There is a developer behind every piece of code!
DNA is too complex what about it!
No junk DNA; There is a functional role for noncoding DNA

Comments and Discussions

 
QuestionWarning: include(z-ad.php): failed to open stream Pin
Salam Y. ELIAS5-May-21 0:29
professionalSalam Y. ELIAS5-May-21 0:29 
AnswerRe: Warning: include(z-ad.php): failed to open stream Pin
NewPast7-May-21 2:29
NewPast7-May-21 2:29 
GeneralRe: Warning: include(z-ad.php): failed to open stream Pin
Salam Y. ELIAS7-May-21 5:48
professionalSalam Y. ELIAS7-May-21 5:48 
GeneralRe: Warning: include(z-ad.php): failed to open stream Pin
NewPast7-May-21 8:38
NewPast7-May-21 8:38 
QuestionRequired fields? Pin
peterboulton18-Apr-21 23:54
professionalpeterboulton18-Apr-21 23:54 
AnswerRe: Required fields? Pin
NewPast19-Apr-21 20:17
NewPast19-Apr-21 20:17 
GeneralRe: Required fields? Pin
peterboulton20-Apr-21 4:36
professionalpeterboulton20-Apr-21 4:36 
QuestionBIG Security Problem Pin
JakePogo23-Mar-21 5:22
professionalJakePogo23-Mar-21 5:22 
AnswerRe: BIG Security Problem Pin
NewPast18-Apr-21 4:32
NewPast18-Apr-21 4:32 
PraisePretty Good Efforts Pin
MayurDighe21-Oct-16 4:43
professionalMayurDighe21-Oct-16 4:43 
QuestionInjection Protection - Sanitising and Validating Pin
M-Badger20-Oct-16 18:35
M-Badger20-Oct-16 18:35 
Hi,

I'm not sure your code does everything needed to protect against injection, I think you are only validating and not sanitising. Sanitising is more critical in injection protection.

PHP
if (!filter_var($from_email, FILTER_VALIDATE_EMAIL))


It's a while since I looked at the subject but as a minimum I think you need to use FILTER_SANITIZE_EMAIL as well.
I looked at this subject a few years ago (so it might be a bit out of date), I looked only briefly at FILTER_SANITIZE_EMAIL and FILTER_VALIDATE_EMAIL and discarded them since they were a "black box" solution that I could not judge the quality of.

M
AnswerRe: Injection Protection - Sanitising and Validating Pin
NewPast20-Oct-16 20:39
NewPast20-Oct-16 20:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.