Giter VIP home page Giter VIP logo

raspgot / contact-form-php Goto Github PK

View Code? Open in Web Editor NEW
58.0 58.0 14.0 426 KB

Simple, customizable and secure bootstrap contact form Jquery FREE using Ajax, validations inputs, SMTP protocol, rejected domain and Google reCAPTCHA v3.

Home Page: https://dev.raspgot.fr/github/contact-form-php

PHP 44.74% HTML 29.15% JavaScript 26.11%
ajax bootstrap captcha form javascript php phpmailer recaptcha smtp

contact-form-php's Introduction

  • πŸ‘‹ Hi, I’m @raspgot
  • πŸ‘€ I’m interested in PHP, Javascript, C#, SQL, CSS
  • 🌱 I’m currently learning Laravel and Symfony
  • πŸ’žοΈ I’m looking to collaborate on freelance project
  • πŸ“« How to reach me ? Just here

contact-form-php's People

Contributors

raspgot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

contact-form-php's Issues

SMTP Error: Could not authenticate ?

Hello,
I believe I did everything right, but I get this error, what is the reason ? SMTP Error: Could not authenticate ?

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

# https://www.php.net/manual/fr/timezones.php
date_default_timezone_set('America/Los_Angeles');

require __DIR__ . '/vendor/PHPMailer/Exception.php';
require __DIR__ . '/vendor/PHPMailer/PHPMailer.php';
require __DIR__ . '/vendor/PHPMailer/SMTP.php';
require __DIR__ . '/vendor/recaptcha/autoload.php';

class Ajax_Form {
    
    # Constants to redefined
    const HOST        = 'srvm05.trwww.com'; # SMTP server
    const USERNAME    = '*********.com '; # SMTP username
    const PASSWORD    = '*******'; # SMTP password
    const SMTP_SECURE = PHPMailer::ENCRYPTION_STARTTLS;
    const SMTP_AUTH   = true;
    const PORT        = 25;
    const SECRET_KEY  = ' 6LfBj6oZAAAAAMFgH9SJ3g4VqkK1MmpEomi55XOm '; # GOOGLE secret key
    const SUBJECT     = 'New message !';
    public $handler   = [
        'success'       => 'βœ”οΈ Your message has been sent.',
        'token-error'   => '❌ Error recaptcha token.',
        'enter_name'    => '❌ Please enter your name.',
        'enter_email'   => '❌ Please enter a valid email.',
        'enter_message' => '❌ Please enter your message.',
        'ajax_only'     => '❌ Asynchronous anonymous.',
        'body'          => '
            <h1>{{subject}}</h1>
            <p><strong>Date :</strong> {{date}}</p>
            <p><strong>Name :</strong> {{name}}</p>
            <p><strong>E-Mail :</strong> {{email}}</p>
            <p><strong>Message :</strong> {{message}}</p>
        ',
    ];

    /**
     * Ajax_Form __constructor
     */
    public function __construct() {

        # Check if request is Ajax request
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XMLHttpRequest' !== $_SERVER['HTTP_X_REQUESTED_WITH']) {
            $this->statusHandler('ajax_only', 'error');
        }

        # Check if fields has been entered and valid
        # Get secure post data
        $name    = !empty($_GET['name']) ? filter_var($this->secure($_GET['name']), FILTER_SANITIZE_STRING) : $this->statusHandler('enter_name');
        $email   = !empty($_GET['email']) ? filter_var($this->secure($_GET['email']), FILTER_SANITIZE_EMAIL) : $this->statusHandler('enter_email');
        $message = !empty($_GET['message']) ? filter_var($this->secure($_GET['message']), FILTER_SANITIZE_STRING) : $this->statusHandler('enter_message');
        $token   = !empty($_GET['recaptcha-token']) ? filter_var($this->secure($_GET['recaptcha-token']), FILTER_SANITIZE_STRING) : $this->statusHandler('token-error');
        $date    = new DateTime();

        # Prepare body
        $body = $this->getString('body');
        $body = $this->template( $body, [
            'subject' => self::SUBJECT,
            'date'    => $date->format('j/m/Y H:i:s'),
            'name'    => $name,
            'email'   => $email,
            'message' => $message,
        ] );

        # Verifying the user's response
        $recaptcha = new \ReCaptcha\ReCaptcha(self::SECRET_KEY);
        $resp = $recaptcha
            ->setExpectedHostname($_SERVER['SERVER_NAME'])
            ->verify($token, $_SERVER['REMOTE_ADDR']);
            
        if ($resp->isSuccess()) {

            $mail = new PHPMailer(true);
            $mail->setLanguage('en', __DIR__ . '/vendor/PHPMailer/language/');

            try {
                # Server settings
                $mail->SMTPDebug  = SMTP::DEBUG_OFF;   # Enable verbose debug output
                $mail->isSMTP();                       # Set mailer to use SMTP
                $mail->Host       = self::HOST;        # Specify main and backup SMTP servers
                $mail->SMTPAuth   = self::SMTP_AUTH;   # Enable SMTP authentication
                $mail->Username   = self::USERNAME;    # SMTP username
                $mail->Password   = self::PASSWORD;    # SMTP password
                $mail->SMTPSecure = self::SMTP_SECURE; # Enable TLS encryption, `ssl` also accepted
                $mail->Port       = self::PORT;        # TCP port
            
                # Recipients
                $mail->setFrom(self::USERNAME, 'Raspgot');
                $mail->addAddress($email, $name);
                $mail->AddCC(self::USERNAME, 'Dev_copy');
                $mail->addReplyTo(self::USERNAME, 'Information');
            
                # Content
                $mail->CharSet = 'UTF-8';
                $mail->isHTML(true);
                $mail->Subject = self::SUBJECT;
                $mail->Body    = $body;
                $mail->AltBody = strip_tags($body);;
            
                $mail->send();
                $this->statusHandler('success');

            } catch (Exception $e) {
                die (json_encode( $mail->ErrorInfo ));
            }
        } else {
            die (json_encode( $resp->getErrorCodes() ));
        }
    }

    /**
     * Template string
     *
     * @param string $string
     * @param array $vars
     * @return string
     */
    public function template($string, $vars)
    {
        foreach ($vars as $name => $val) {
            $string = str_replace("{{{$name}}}", $val, $string);
        }
        return $string;
    }

    /**
     * Get string from $string variable
     *
     * @param string $string
     * @return string
     */
    public function getString($string)
    {
        return isset($this->handler[$string]) ? $this->handler[$string] : $string;
    }

    /**
     * Secure inputs fields
     *
     * @param string $post
     * @return string
     */
    public function secure($post)
    {
        $post = htmlspecialchars($post);
        $post = stripslashes($post);
        $post = trim($post);
        return $post;
    }

    /**
     * Error or success message
     *
     * @param string $message
     * @param string $status
     * @return json
     */
    public function statusHandler($message)
    {
        die (json_encode($this->getString($message)));
    }

}

# Instanciation 
new Ajax_Form();
 

Adding checkboxes?

I've taken your code and been trying to add to it, specifically adding checkboxes in an array. However, I am still coming up with an undefined variable if the checkboxes are skipped.

Any chance you can help with this? I am sure I'm not the only person who's said "it would be nice to have checkboxes in a form"

Thanks

class Ajax_Form {
    # Constants to redefined
    # Check this for more configurations: https://blog.mailtrap.io/phpmailer
    const HOST        = 'mail.bluehonudesign.com'; # SMTP server
    const USERNAME    = '*******@bluehonudesign.com'; # SMTP username
    const PASSWORD    = '*****'; # SMTP password
    const SECRET_KEY  = '6LcKHswiAAAAACS-R11KgDa92U76S1LVQPCbsGBc'; # GOOGLE secret key
    const SMTP_SECURE = PHPMailer::ENCRYPTION_STARTTLS;
    const SMTP_AUTH   = true;
    const PORT        = 587;
    const SUBJECT     = 'Contact Form Message';
    const HANDLER_MSG = [
        'success'       => '<strong>βœ”οΈ Your message has been sent!</strong><br>
        We will be sure to return your message shortly. Thanks!',
        'token-error'   => '❌ Error recaptcha token.',
        'enter_name'    => '❌ Please enter your name.',
        'enter_email'   => '❌ Please enter a valid email.',
        'enter_message' => '❌ Please enter your message.',
        'enter_phone' => '❌ Please enter your phone number.',
        'bad_ip'        => '❌ 56k ?',
        'ajax_only'     => '❌ Asynchronous anonymous.',
        'email_body'    => '
            <style>
            body {
                font-family: arial, helvetica, sans-serif !important;                                                
            }
            table {
                width: 100%;
                margin: 20px auto;
                table-layout: auto;
            }

            .fixed {
                table-layout: fixed;
            }

            table, td, th {
                border-collapse: collapse;
            }

            th, td {
                padding: 10px;
                border: none;
                border-bottom: 1px dotted #ccc;
                text-align: left;
                vertical-align: top;
                font-size: 1rem;
            }

            td:first-child {
                width: 100px;
            }
            </style>
           
            <table>
            <tr><td colspan="2"><h1>{{subject}}</h1></td></tr>
            <tr><td><b>Date</b>:</td><td>{{date}}</td></tr>
            <tr><td><b>Name</b>:</td><td>{{name}}</td></tr>
            <tr><td><b>E-Mail</b>:</td><td>{{email}}</td></tr>
            <tr><td><b>Phone</b>:</td><td>{{phone}}</td></tr>
            <tr><td><b>Best time to call</b>:</td><td>{{when}}</td></tr>
            <tr><td colspan="2"><br></td></tr>
            <tr><td><b>Current website</b>:</td><td>{{website}}</td></tr>
            <tr><td><b>Interested In</b>:</td><td>{{service}}</td></tr>
            <tr><td colspan="2"><br></td></tr>
            <tr><td><b>Address</b>:</td><td>{{address1}}<br>
                                            {{address2}}<br>
                                            {{city}}, {{state}} {{zip}}</td></tr>
            <tr><td colspan="2"><br></td></tr>
            <tr><td><b>Referring source</b>:</td><td>{{howfind}}</td></tr>
            <tr><td><b>Message</b>:</td><td>{{message}}</td></tr>
            <tr><td><b>IP</b>:</td><td>{{ip}}</td></tr>
            </table>
        '
    ];

    /**
     * Ajax_Form constructor
     */
    public function __construct()
    {
        # Check if request is Ajax request
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest') {
            $this->statusHandler('ajax_only');
        }

        # Check if fields has been entered and valid
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $name    = $this->secure($_POST['name']) ?? $this->statusHandler('enter_name');
            $email   = filter_var($this->secure($_POST['email']), FILTER_SANITIZE_EMAIL) ?? $this->statusHandler('enter_email');
            $message = $this->secure($_POST['message']) ?? $this->statusHandler('enter_message');
            $phone = $this->secure($_POST['phone']) ?? $this->statusHandler('enter_phone');
            $token   = $this->secure($_POST['recaptcha-token']) ?? $this->statusHandler('token-error');
            $ip      = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP) ?? $this->statusHandler('bad_ip');
            $date    = new DateTime();
            $address1 = $this->secure($_POST['address1']) ?? $this->statusHandler('enter_address1');
            $address2 = $this->secure($_POST['address2']);
            $city = $this->secure($_POST['city']);
            $state = filter_input(INPUT_POST, 'state', FILTER_UNSAFE_RAW);
            $zip = $this->secure($_POST['zip']);
            $when = filter_input(INPUT_POST, 'when', FILTER_UNSAFE_RAW);
            if (isset($_POST['howfind'])) {
               $howfind = implode(',', $_POST['howfind']);
               } else 
                    if (empty(['howfind'])) 
                         echo"foo";

            if (isset($_POST['service'])) {
               $service = implode(',', $_POST['service']);
               } else 
               if (empty(['service'])) 
                    echo"foo";
            $website = $this->secure($_POST['website']);
          };

        # Prepare email body
        $email_body = self::HANDLER_MSG['email_body'];
        $email_body = $this->template($email_body, [
            'subject'   => self::SUBJECT,
            'date'      => $date->format('j/m/Y H:i:s'),
            'name'      => $name,
            'phone'     => $phone,
            'email'     => $email,
            'ip'        => $ip,
            'address1'  => $address1,
            'address2'  => $address2,
            'city'      => $city,
            'state'     => $state,
            'zip'       => $zip,
            'message'   => $message,
            'website'   => $website,
            'howfind'   => $howfind,
            'service'   => $service,
            'when'      => $when,
            
        ]);

        # Verifying the user's response
        $recaptcha = new \ReCaptcha\ReCaptcha(self::SECRET_KEY);
        $resp = $recaptcha
            ->setExpectedHostname($_SERVER['SERVER_NAME'])
            ->verify($token, $_SERVER['REMOTE_ADDR']);

        if ($resp->isSuccess()) {
            # Instanciation of PHPMailer
            $mail = new PHPMailer(true);
            $mail->setLanguage('en', __DIR__ . '/vendor/PHPMailer/language/');

            try {
                # Server settings
                $mail->SMTPDebug  = SMTP::DEBUG_OFF;   # Enable verbose debug output
                $mail->isSMTP();                       # Set mailer to use SMTP
                $mail->Host       = self::HOST;        # Specify main and backup SMTP servers
                $mail->SMTPAuth   = self::SMTP_AUTH;   # Enable SMTP authentication
                $mail->Username   = self::USERNAME;    # SMTP username
                $mail->Password   = self::PASSWORD;    # SMTP password
                $mail->SMTPSecure = self::SMTP_SECURE; # Enable TLS encryption, `ssl` also accepted
                $mail->Port       = self::PORT;        # TCP port
                
                # Recipients
                
                # $mail->setFrom(self::USERNAME, $name);
                # $mail->addAddress("[email protected]");
                #$mail->addAddress($email, $name);
                # $mail->AddCC(self::USERNAME, 'Dev_copy');
                # $mail->addReplyTo(self::USERNAME, $email);

                $mail->setFrom($email, $name);
                $mail->addAddress('[email protected]');
                # $mail->AddCC(self::USERNAME);
                $mail->addReplyTo($email, $name);

                $mail->SMTPOptions = array(
                    'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                    )
                );

                # Content
                $mail->isHTML(true);
                $mail->CharSet = 'UTF-8';
                $mail->Subject = self::SUBJECT;
                $mail->Body    = $email_body;
                $mail->AltBody = strip_tags($email_body);

                # Send email
                $mail->send();
                $this->statusHandler('success');

            } catch (Exception $e) {
                die(json_encode($mail->ErrorInfo));
            }
        } else {
            die(json_encode($resp->getErrorCodes()));
        }
    }
}

Contact form not submitting

On localhost getting error
{"error":true,"message":["missing-input-response"]}

on Live
This page isn’t working right now
xxxxx.co.uk can't currently handle this request.
HTTP ERROR 500

Missing Input Response

Hello,

I've already set up Site Key, SMTP details, Secret Key and when I've submit the form, I do receive
["missing-input-response"]

Additionally, when I try to submit form without Captcha, it still lets me do it.

Uncaught ReferenceError: e is not defined

I have an error in the console and when I submit the form I get the error "missing-input-response". I have seen the other posts about this error but could not fix it.

Console Error:

AjaxForm.js:68 Uncaught ReferenceError: e is not defined at checkRecaptcha (AjaxForm.js:68:5) at onload (AjaxForm.js:16:5)

I have checked the keys several times and proceeded as in the instructions.

JS: const reCAPTCHA_site_key
PHP: const SECRET_KEY
HTML: api.js?render=

I have also checked the URL which is also correct, have also created a new website with new keys, unfortunately without success.

I can't get figure out

Here is the form: https://www.nighthub.ch/

Thanks for your help

Error: HOSTNAME_MISMATCH

Issue description
I get the error: hostname-mismatch. I am sure that I have entered the private and public keys correctly as per the instructions. This error is described in the ReCaptcha.php file as highlighted below, but I am not sure what is triggering it.

    /**
     * Expected hostname did not match
     * @const string
     */
    const E_HOSTNAME_MISMATCH = 'hostname-mismatch';

Environment
OS name and version: Windows 10 Pro
PHP version: PHP 8.0.3
Web server name and version: ubuntu 20.04
google/ReCaptcha version: v.3
Browser name and version: Chrome 89.0.4389.90 (Official Build) (64-bit)

How can I solve this error?

Not working. Demo not working

Hello!
It is not working. Not even the demo is not working. I have no error what so ever.
I don't know what to do
Thank you!

Admin popup with error connection-failedhostname-mismatch

on form submission:
Admin popup with errror message: connection-failedhostname-mismatch
of course the site keys with google recaptcha v3 were registered with correct domain both with and w/o www
sometimes in v2 there were request problems with ssl protected forms, cannot believe that is still problematic?
have you got an idea @raspgot ?

Merci

SyntaxError Json line 59

Hello,

I am trying to use this form on my website. I changed only the fields indicated in the "readme". But an error appears when I try to send an email. Would you help me?

VM263:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Object.<anonymous> (AjaxForm.js:59)
    at c (jquery-3.4.1.min.js:2)
    at Object.fireWith [as resolveWith] (jquery-3.4.1.min.js:2)
    at l (jquery-3.4.1.min.js:2)
    at XMLHttpRequest.<anonymous> (jquery-3.4.1.min.js:2)

Uncaught ReferenceError: angular is not defined

Hello,

My problem send . Click Send, script stop, button name will change to SENDING.... and STOP :(

Console error:

Uncaught ReferenceError: angular is not defined
    submitHandler https://xxxxxxx/AjaxForm.js:58
    jQuery 7
    submitHandler https://xxxxxxx/AjaxForm.js:56
    jQuery 11
    <anonymous> https://xxxxxxx/AjaxForm.js:14
    jQuery 13

Thank you.

error when cookie is rejected

hello,

I am implementing my cookie notice and everything related. well the case is that when someone rejects the cookies and tries to submit the form I get the error " {"code":"MethodNotAllowed","message":"POST is not allowed"} ".

I know that this error appears because there is no token because the cookies have been blocked. My question is, is there any way that if the cookies have already been rejected the send button is deactivated or, failing that, a message appears saying that there is than accept cookies

SyntaxError: JSON.parse

I think I settled everything as instructed. The form is able sent and I get an email, but there is a constant error in the console on Chrome and on Mozilla. And because it always an error on JSON, the visitor who sends the form cannot see the successful send message.
With chrome it is the following:
Error encountered: SyntaxError: unexpected token '<',"
< b >"... is not valid JSON

With Mozilla:
Error encountered: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Checkboxes

I've downloaded the code and made it work... until I introduced checkboxes. Now it's choking.

The error I am getting is:

PHP Warning: Undefined array key "instype[]" in /home1/bluehqwi/public_html/gowithfm/quote/AjaxForm.php on line 91 PHP Fatal error: Uncaught TypeError: Ajax_Form::secure(): Argument #1 ($post) must be of type string, null given, called in /home1/bluehqwi/public_html/gowithfm/quote/AjaxForm.php on line 91 and defined in /home1/bluehqwi/public_html/gowithfm/quote/AjaxForm.php:184 Stack trace: #0 /home1/bluehqwi/public_html/gowithfm/quote/AjaxForm.php(91): Ajax_Form->secure(NULL) #1 /home1/bluehqwi/public_html/gowithfm/quote/AjaxForm.php(207): Ajax_Form->__construct() #2 {main} thrown in /home1/bluehqwi/public_html/gowithfm/quote/AjaxForm.php on line 184

My code after I have edited it is:

PHP Warning:  Undefined array key "instype[]" in /home1/bluehqwi/public_html/gowithfm/quote/AjaxForm.php on line 91
PHP Fatal error:  Uncaught TypeError: Ajax_Form::secure(): Argument #1 ($post) must be of type string, null given, called in /home1/bluehqwi/public_html/gowithfm/quote/AjaxForm.php on line 91 and defined in /home1/bluehqwi/public_html/gowithfm/quote/AjaxForm.php:184
Stack trace:
#0 /home1/bluehqwi/public_html/gowithfm/quote/AjaxForm.php(91): Ajax_Form->secure(NULL)
#1 /home1/bluehqwi/public_html/gowithfm/quote/AjaxForm.php(207): Ajax_Form->__construct()
#2 {main}
  thrown in /home1/bluehqwi/public_html/gowithfm/quote/AjaxForm.php on line 184

The code I am using is:

<?php

/**
 * Simple and secure contact form using Ajax, validations inputs, SMTP protocol and Google reCAPTCHA v3 in PHP.
 * 
 * @see      https://github.com/raspgot/AjaxForm-PHPMailer-reCAPTCHA
 * @package  PHPMailer | reCAPTCHA v3
 * @author   Gauthier Witkowski <[email protected]>
 * @link     https://raspgot.fr
 * @version  1.1.0
 */

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

# https://www.php.net/manual/timezones.php
date_default_timezone_set('America/Los_Angeles');

require __DIR__ . '/../PHPMailer/Exception.php';
require __DIR__ . '/../PHPMailer/PHPMailer.php';
require __DIR__ . '/../PHPMailer/SMTP.php';
require __DIR__ . '/../recaptcha/autoload.php';

class Ajax_Form {

    # Constants to redefined
    # Check this for more configurations: https://blog.mailtrap.io/phpmailer
    const HOST        = 'XXXXX'; # SMTP server
    const USERNAME    = 'XXXXX'; # SMTP username
    const PASSWORD    = 'XXXXX'; # SMTP password
    const SECRET_KEY  = 'XXXXX'; # GOOGLE secret key
    const SMTP_SECURE = PHPMailer::ENCRYPTION_STARTTLS;
    const SMTP_AUTH   = true;
    const PORT        = 587;
    const SUBJECT     = 'XXXXX';
    const HANDLER_MSG = [
        'success'       => 'βœ”οΈ Your message has been sent !',
        'token-error'   => '❌ Error recaptcha token.',
        'enter_firstname'    => '❌ Please enter your first name.',
		'enter_lastname'    => '❌ Please enter your last name.',
        'enter_email'   => '❌ Please enter a valid email.',
		'enter_phone' => '❌ Please enter a valid phone number.',
        'enter_message' => '❌ Please enter your message.',
        'bad_ip'        => '❌ 56k ?',
        'ajax_only'     => '❌ Asynchronous anonymous.',
        'email_body'    => '
            <h1>{{subject}}</h1>
			<p><b>First name:</b> {{firstname}}</p>
			<p><b>Last name:</b> {{lastname}}</p>
			<p><b>Email:</b> {{email}}</p>
			<p><b>Phone:</b> {{phone}}</p>
			<p><b>Address 1:</b> {{address1}}</p>
			<p><b>Address 2:</b> {{address2}}</p>
			<p><b>City:</b> {{city}}</p>
			<p><b>State:</b> {{state}}</p>
			<p><b>Zip:</b> {{zip}}</p>
			<p><b>Interested in:</b> {{instype}}</p>
'
    ];
			
			/* <p><b>Date</b>: {{date}}</p>
            <p><b>Name</b>: {{name}}</p>
            <p><b>E-Mail</b>: {{email}}</p>
            <p><b>Message</b>: {{message}}</p>
            <p><b>IP</b>: {{ip}}</p>
        ' 
    ];*/

    /**
     * Ajax_Form constructor
     */
    public function __construct()
    {
        # Check if request is Ajax request
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest') {
            $this->statusHandler('ajax_only');
        }

        # Check if fields has been entered and valid
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $firstname    = $this->secure($_POST['firstname']) ?? $this->statusHandler('enter_name');
			$lastname    = $this->secure($_POST['firstname']) ?? $this->statusHandler('enter_name');
            $email   = filter_var($this->secure($_POST['email']), FILTER_SANITIZE_EMAIL) ?? $this->statusHandler('enter_email');
            $phone = $this->secure($_POST['phone']) ?? $this->statusHandler('enter_phone');
			$address1 = $this->secure($_POST['address1']) ?? $this->statusHandler('enter_address1');
			$address2 = $this->secure($_POST['address2']) ?? $this->statusHandler('enter_address2');
			$city = $this->secure($_POST['city']) ?? $this->statusHandler('enter_city');
			$state = $this->secure($_POST['state']) ?? $this->statusHandler('enter_state');
			$zip = $this->secure($_POST['zip']) ?? $this->statusHandler('enter_zip');
			$instype = $this->secure($_POST['instype']) ?? $this->statusHandler('enter_instype');
			# $message = $this->secure($_POST['message']) ?? $this->statusHandler('enter_message');
            $token   = $this->secure($_POST['recaptcha-token']) ?? $this->statusHandler('token-error');
            $ip      = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP) ?? $this->statusHandler('bad_ip');
            $date    = new DateTime();
        }

        # Prepare email body
        $email_body = self::HANDLER_MSG['email_body'];
        $email_body = $this->template($email_body, [
            'subject' => self::SUBJECT,
            'date'    => $date->format('j/m/Y H:i:s'),
            'firstname' => $firstname,
			'lastname' => $lastname,
			'email' => $email,
			'phone' => $phone,
			'address1' => $address1,
			'address2' => $address2,
			'city' => $city,
			'state' => $state,
			'zip' => $zip,
			'instype' => $instype
        ]);

        # Verifying the user's response
        $recaptcha = new \ReCaptcha\ReCaptcha(self::SECRET_KEY);
        $resp = $recaptcha
            ->setExpectedHostname($_SERVER['SERVER_NAME'])
            ->verify($token, $_SERVER['REMOTE_ADDR']);
            
        if ($resp->isSuccess()) {
            # Instanciation of PHPMailer
            $mail = new PHPMailer(true);
            $mail->setLanguage('en', __DIR__ . '/vendor/PHPMailer/language/');

            try {
                # Server settings
                $mail->SMTPDebug  = SMTP::DEBUG_OFF;   # Enable verbose debug output
                $mail->isSMTP();                       # Set mailer to use SMTP
                $mail->Host       = self::HOST;        # Specify main and backup SMTP servers
                $mail->SMTPAuth   = self::SMTP_AUTH;   # Enable SMTP authentication
                $mail->Username   = self::USERNAME;    # SMTP username
                $mail->Password   = self::PASSWORD;    # SMTP password
                $mail->SMTPSecure = self::SMTP_SECURE; # Enable TLS encryption, `ssl` also accepted
                $mail->Port       = self::PORT;        # TCP port

                # Recipients
                $mail->setFrom(self::USERNAME, $firstname, $lastname);
                $mail->addAddress($email, $firstname, $lastname);
                $mail->AddCC(self::USERNAME, 'Dev_copy');
                $mail->addReplyTo(self::USERNAME, 'Information');

                # Content
                $mail->isHTML(true);
                $mail->CharSet = 'UTF-8';
                $mail->Subject = self::SUBJECT;
                $mail->Body    = $email_body;
                $mail->AltBody = strip_tags($email_body);

                # Send email
                $mail->send();
                $this->statusHandler('success');

            } catch (Exception $e) {
                die(json_encode($mail->ErrorInfo));
            }
        } else {
            die(json_encode($resp->getErrorCodes()));
        }
    }

    /**
     * Template string values
     *
     * @param string $string
     * @param array $vars
     * @return string
     */
    public function template(string $string, array $vars): string
    {
        foreach ($vars as $name => $val) {
            $string = str_replace("{{{$name}}}", $val, $string);
        }

        return $string;
    }

    /**
     * Secure inputs fields
     *
     * @param string $post
     * @return string
     */
    public function secure(string $post): string
    {
        $post = htmlspecialchars($post, ENT_QUOTES);
        $post = stripslashes($post);
        $post = trim($post);

        return $post;
    }

    /**
     * Error or success message
     *
     * @param string $message
     * @return json
     */
    public function statusHandler(string $message): json
    {
        die(json_encode(self::HANDLER_MSG[$message]));
    }

}

# Instanciation 
new Ajax_Form();


I'll be the first to admit I'm not that great at PHP.

How can I use checkboxes in my form with your script?

(Note: I replaced my SMTP and reCaptcha info with XXXXX for security reasons in this post)

Thanks

timeout-or-duplicatehostname-mismatch

Hello,

As i see the closed issues this error is related to reCAPTCHA, but I dont use subdomains for my contact form.
I think I got this error when not touching the site and the reCAPTCHA is expired, but my biggest problem is in this error the contact form goes empty, all entered texts destory.

How can we deal this?

Thanks for your help, your project is really nice!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.