Phone field on Contact form

Hi Folks,

First post here (I’m a complete newbie when it comes to php) and I know you’ll probably want to beat me around the head with a blunt object when you see what I’m asking, but I haven’t a clue when it comes to php and just trying to jump in the deep end and get this contact form up and running! It’s currently working, but I need to add a phone number field, I can probably add it to the contact form, but where and what would I add to the php script?

I’d appreciate if someone could take a minute and let me know what to do here…!

Here’s the form:

[php]




First Name






Last Name






Email Address






Question or Comment







Send



[/php]

And the Php Script:

[php]

<?php if(isset($_POST['email'])) { // EDIT THE 2 LINES BELOW AS REQUIRED $email_to = "[email protected]"; $email_subject = "Email from contact form"; function died($error) { // your error code can go here echo "We are very sorry, but there were error(s) found with the form you submitted. "; echo "These errors appear below.

"; echo $error."

"; echo "Please go back and fix these errors.

"; die(); } // validation expected data exists if(!isset($_POST['first_name']) || !isset($_POST['last_name']) || !isset($_POST['email']) || !isset($_POST['comments'])) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } $first_name = $_POST['first_name']; // required $last_name = $_POST['last_name']; // required $email_from = $_POST['email']; // required $comments = $_POST['comments']; // required $error_message = ""; $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if(!preg_match($email_exp,$email_from)) { $error_message .= 'The Email Address you entered does not appear to be valid.
'; } $string_exp = "/^[A-Za-z\s.'-]+$/"; if(!preg_match($string_exp,$first_name)) { $error_message .= 'The First Name you entered does not appear to be valid.
'; } if(!preg_match($string_exp,$last_name)) { $error_message .= 'The Last Name you entered does not appear to be valid.
'; } if(strlen($comments) < 2) { $error_message .= 'The Comments you entered do not appear to be valid.
'; } if(strlen($error_message) > 0) { died($error_message); } $email_message = "Form details below.\n\n"; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "First Name: ".clean_string($first_name)."\n"; $email_message .= "Last Name: ".clean_string($last_name)."\n"; $email_message .= "Email: ".clean_string($email_from)."\n"; $email_message .= "Comments: ".clean_string($comments)."\n"; // create email headers $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); sleep(2); echo ""; ?> <?php } ?>[/php]

Hi again Folks,
Am I in the wrong place to ask the question above? Nobody seems to want to help and I’m wondering if I’ve done something wrong in asking for help.

Is it a case that I should be paying for a mail script, and if so, where’s the best place to buy a customised script?

Thanks for reading…!

Personally I use Swiftmailer as my email client that way I don’t have to come up with my own script(s). I am in the process of starting my own small printing company and in the process of designing and developing the website for it. I just so happen to be in in the middle of doing my contact page and I have the form done. I show it it to you for maybe it will give you pointers or help?

The whole thing is basically on one page with the exception of some configuration pages and Swiftmailer. Here’s the PHP and HTML

[php]<?php
include_once ‘vendor/swiftmailer/swiftmailer/lib/swift_required.php’;
require_once ‘lib/includes/utilities.inc.php’;

/*

  • Send Email to Adminstrator
    */

function send_email(array $data) {
/* Setup swiftmailer using your email server information */
if (filter_input(INPUT_SERVER, ‘SERVER_NAME’, FILTER_SANITIZE_URL) == “localhost”) {
$transport = Swift_SmtpTransport::newInstance(EMAIL_HOST, EMAIL_PORT); // 25 for remote server 587 for localhost:
} else {
$transport = Swift_SmtpTransport::newInstance(EMAIL_HOST, 25);
}

$transport->setUsername(EMAIL_USERNAME);
$transport->setPassword(EMAIL_PASSWORD);

/* Setup To, From, Subject and Message */
$message = Swift_Message::newInstance();

$name = $data['name'];
$subject = $data['reason'];
$email_from = $data['email'];
if (trim($data['phone']) !== NULL) {
    $comments = $name . ' (' . $data['phone'] . ') wrote the following: ' . $data['comments'];
} else {
    $comments = $name . ' wrote the following: ' . $data['comments'];
}

$message->setTo([
    '[email protected]' => 'John Smith'
]);

$message->setSubject($subject); // Subject:
$message->setBody($comments); // Message:
$message->setFrom($email_from, $name); // From and Name:

$mailer = Swift_Mailer::newInstance($transport); // Setting up mailer using transport info that was provided:
$result = $mailer->send($message, $failedRecipients);

if ($result) {
    return TRUE;
} else {
    echo "<pre>" . print_r($failedRecipients, 1) . "</pre>";
    return FALSE;
}

}

$error = [];

function blankCheck($temp) {
$error = isset($temp) ? trim($temp) : ‘’;
if ($error == “”) {
return true;
}
}

$submit = filter_input(INPUT_POST, ‘action’, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

if (isset($submit) && $submit === ‘enter’) {
/* The Following to get response back from Google recaptcah */
$url = “https://www.google.com/recaptcha/api/siteverify”;

$remoteServer = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_SANITIZE_URL);
$response = file_get_contents($url . "?secret=" . PRIVATE_KEY . "&response=" . \htmlspecialchars($_POST['g-recaptcha-response']) . "&remoteip=" . $remoteServer);
$recaptcha_data = json_decode($response);
/* The actual check of the recaptcha */
if (isset($recaptcha_data->success) && $recaptcha_data->success === TRUE) {
    $data['name'] = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $data['email'] = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $data['phone'] = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $data['reason'] = filter_input(INPUT_POST, 'reason', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $data['comments'] = filter_input(INPUT_POST, 'comments', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $error[0] = blankCheck($data['name']);
    $error[1] = blankCheck($data['email']);
    $error[2] = blankCheck($data['comments']);

    if (!in_array(true, $error, true)) {
        send_email($data);
    }
}

}

require_once ‘lib/includes/header.inc.php’;
?>

        <fieldset>

            <legend>Contact Form</legend>
            <input type="hidden" name="action" value="enter">
            <label for="name" accesskey="U">Your Name</label>
            <input name="name" type="text" id="name" placeholder="Enter your name" required="required" />

            <label for="email" accesskey="E">Email</label>
            <input name="email" type="email" id="email" placeholder="Enter your Email Address" required="required" />

            <label for="phone" accesskey="P">Phone <small>(optional)</small></label>
            <input name="phone" type="tel" id="phone" size="30" placeholder="Enter your phone number" />

        </fieldset>

        <fieldset>

            <legend>Your Comments</legend>

            <div class="radioBlock">
                <input type="radio" id="radio1" name="reason" value="question" checked>
                <label class="radioStyle" for="radio1">question</label>
                <input type="radio" id="radio2" name="reason" value="order status">
                <label class="radioStyle" for="radio2">status</label>
                <input type="radio" id="radio3" name="reason" value="comment">
                <label class="radioStyle" for="radio3">comment</label>
            </div>

            <label class="textBox" for="comments">Comments</label>
            <textarea name="comments" id="comments" placeholder="Enter your comments (required)" spellcheck="true" required="required"></textarea>
            <div class="g-recaptcha" data-sitekey="6Lel2hsUAAAAAOGxdZaaZ2BwcMBC7sSr86P4f6QG"></div>
            <input type="submit" name="submit" value="submit">
        </fieldset>

    </form>
</div>
<?php require_once 'lib/includes/footer.inc.php'; [/php]

I still have to write a “This email was successfully sent!” or “The were a problem sending, please correct and try again” message, but it works. I also rely on HTML5 to successfully block in sending a blank email, but I have written some php to backup in case it doesn’t work. I have found out in the past that some mobile device and tablets don’t recognize HTML5 for some strange reason? I have also added Google’s reCaptcha in hopes of stopping most spammers.
Anyway to see it in action click here -> https://www.buystuffright.com/contact.php

Anyways I hope this is some help?

John

P.S. I just notice I should really log the error message if the email fails instead of showing the error for my production website. I’ll be correcting that.

Strider64,

I’ve downloaded Swiftmailer to take a look at it and see if I can get a handle on the way it works. I realise I should really start at the beginning with PHP and learn it from the ground up. The only time I’ve used php is to include sections into web pages, apart from that I know nothing! I’m facing an uphill struggle, but we all have to start somewhere and by you including your contact page I can perhaps reverse engineer and learn a bit that way.

I used to have a windows program that would generate a sendmail script for me from a html form page and that was really easy to work with, I’ll probably have a few sleepless nights trying to figure out how to use the Swiftmailer but at least I’m being pointed in a positive direction and am assured that it’s something thats recommended and works at the end of the day.

Thanks a lot for your help on this one - I appreciate it…!

The function send_email is basically all you really need to look at and the EMAIL_PASSWORD for example using one of many constant that I have in a configuration file.

[php]<?php
define(‘EMAIL_HOST’, ‘your_email_host’);
define(‘EMAIL_USERNAME’, ‘your_email_username’);
define(‘EMAIL_PASSWORD’, ‘your_email_password’);
define(‘EMAIL_ADDRESS’, ‘email_address’);
define(‘EMAIL_PORT’, 587);
if (filter_input(INPUT_SERVER, ‘SERVER_NAME’, FILTER_SANITIZE_URL) == “localhost”) {
define(‘DATABASE_HOST’, ‘local_host’);
define(‘DATABASE_NAME’, ‘mysimpleblog’);
define(‘DATABASE_USERNAME’, ‘database_username’);
define(‘DATABASE_PASSWORD’, ‘database_password’);
define(‘DATABASE_DB’, ‘mysimpleblog’);
} else {
/* REMOTE SERVER CONSTANTS */
define(‘DATABASE_HOST’, ‘remote_database_host’);
define(‘DATABASE_NAME’, ‘remote_database_name’);
define(‘DATABASE_USERNAME’, ‘remote_database_username’);
define(‘DATABASE_PASSWORD’, ‘remote_database_password’);
}[/php]

It serves two purposes the main one is that the configuration file (connect.php in this case) is off the root directory and secondly I can show these scripts without worrying of sharing sensitive personal information of me. 8)

As long as you get the vendor folder containing swiftmailer from using composer or direct download (I pretty positive this is another option) setting up swiftmailer is as simple as doing :
[php]<?php
include_once ‘vendor/swiftmailer/swiftmailer/lib/swift_required.php’;[/php]

Hi John,

I’ve directly downloaded Swiftmailer, does this mean I won’t need to install Composer now? That looks like a bit of a feat in itself!
You’ve given me plenty to go on here, it’ll take me some time to get a handle on how it all works though…

Robbie

Hi Folks, guess what? I’m still at it! I’ve decided to learn PHP from the ground up and I’m making slow progress - but it’s progress!

In the meantime, I’ve decided to go with PHPMailer and completed a tutorial using this. I’m pleased to report that I’ve had great success and everything is working fine.

I have one question that someone might help me out with though, the tutorial has only three fields (name, email & message). I need to add the phone field to the body section of the script but don’t know exactly what way to place it. I have the phone added everywhere else in the code and I’m confident that’s all ok - just one line I need to add to, could someone please advise me on this?

[php]$m->Body = ‘From: ’ . $fields[‘name’] . ’ (’ . $fields[‘email’] . ‘)

’ . $fields[‘message’] . ‘

’;[/php]

Thanks folks!

Sponsor our Newsletter | Privacy Policy | Terms of Service