Contact Us/ Email from users

Hi I’m a first time poster. I’ve been working on a site and this is the first time I attempted to implement a contact form, I used traversy media’s tutorial. I have a site for a client that is currently being hosted and dream host. I have been trying to figure out what the mistake is in my code or if its something server side I’m not doing, and have looked for ways that I may have called back the file incorrectly but I have been having trouble finding out what exactly the problem is.

Here is my code:

<?php 
	$msg = '';
	$msgClass = '';


	if(filter_has_var(INPUT_POST, 'submit')) {
		
		$name = htmlspecialchars($_POST['name']);
		$email = htmlspecialchars($_POST['email']);
		$message = htmlspecialchars($_POST['message']);
	}
 
	//check required fields

		if(!empty($email) && !empty($name) && !empty($message)) {

			if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
			$msg = 'Please use a valid email';
			$msgClass = 'alert-danger!';
			} else {
				$toEmail = '[email protected]';
				$subject = 'Contact Request From' .$name; 
				$body = '<h2>Contact Request</h2>
				<h4>Name</h4><p>' .$name. '</p>
				<h4>Name</h4><p>' .$email. '</p>
				<h4>Name</h4><p>' .$message. '</p>
			';
				//main headers
				$headers = "MIME-version: 1.0" ."\r\n";
				$headers .="Content-Type:text/html;charset=UTF-8" . "
					\r\n";
				//additional headers
				$headers .="From:  " .$name. "<".$email.">". "\r\n";

				if(mail($toEmail, $subject, $body, $headers)) {
					// Email Sent
					$msg = 'Your email has been sent'; 
					$msgClass = 'alert-success'
				} 

			$msg = 'Your email was not sent';
			$msgClass = 'alert-danger';
				}

				}
				} else {
			$msg = 'Please fill in all fields';
			$msgClass = 'alert-danger!';
		}
	}
?>



<!DOCTYPE html>
<html>
<head>
	<title>Contact US</title>
	<link rel="stylesheet" href="https://bootswatch.com/cosmo/bootstrap.min.css">

</head>
<body>
 	<nav class="navbar navbar-default">
 		<div class="container">

 		<div class="navbar-header">
 			<a class="navbar-brand" href="index.php">My Website</a>
 			</div>
 			</div>
 		</nav>
 		<div class="container">
 				<?php if($msg != ''): ?>
 					<div class="alert <?php echo $msgClass; ?>"><?php echo $msg; ?></div>
 				<?php endif; ?>
 			<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
 			<div class="form-group">
 					<label>Name</label>
 					<input type="text" name="name" class="form-control" value="<?php echo isset($_POST['name']) ? $name: '';?> ">
 				</div>
 			<div class="form-group">
 					<label>Email</label>
 					<input type="text" name="email" class="form-control" value="<?php echo isset($_POST['email']) ? $email: '';?> ">
 				</div>
 			
 				<div class="form-group">
 					<label>Name</label>
 					<textarea name="message" class="form-control" value="<?php echo isset($_POST['message']) ? $message: '';?> "></textarea>
 				</div>
 			
 				<br>
 				<button type="submit" name="submit" class="btn btn-primary">Submit</button>
 				</form>
 			</div>

 	</body>


 	</html>

Thanks for any help that any one can give and have a good day.

and what is your problem? Do you get any errors?

1 Like

I connected through dream host, but my domain isn’t receiving the email. I uploaded through sftp on filezilla.

I am afraid there could be many reasons why emails don’t arrive the receiver. You say that your domain does not receive the email. Does it receive a hand written email from your personal mail account? Otherwise try to configure your mailbox settings first. Then try a very basic email from a test php file like so:

mail('[email protected]', 'Mail test', 'This mail has been sent to see if the php mail function works properly.');

Alternatively you could use PHPMailer to send your emails through a SMTP server of your choice. (the one you may use from your ISP)

1 Like

I personally would use a 3rd party mailer (PHPMailer or Swiftmailer - my recommendation) as you don’t have to reinvent the wheel.

Here’s my contact page without of few modificatins to what I put on my webserver:

<?php
require_once '../private/initialize.php';

use Library\Database\Database as DB;
use Library\Email\Email;

$username = \NULL;
$success = "Contact Form";
$token = $_SESSION['token'];
$db = DB::getInstance();
$pdo = $db->getConnection();

$submit = filter_input(INPUT_POST, 'submit', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if (isset($submit) && $submit === 'submit') {
    $token = filter_input(INPUT_POST, 'token', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    if (!empty($token)) {
        if (hash_equals($_SESSION['token'], $token)) {
            /* The Following to get response back from Google recaptcha */
            $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) {
                $success = "Mail was sent!";
                $data['name'] = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $data['email'] = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
                $data['phone'] = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $data['website'] = filter_input(INPUT_POST, 'website', 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);

                $send = new Email($data);
            } else {
                $success = "You're not a human!"; // Not on a production server:
            }
        } else {
            // Log this as a warning and keep an eye on these attempts
        }
    }
}

include '../private/includes/header.inc.php';
?>
<section class="main">

    <form id="contact" name="contact" action="contact.php" method="post"  autocomplete="on">
        <fieldset>
            <legend>Contact Form</legend>
            <input type="hidden" name="token" value="<?= $_SESSION['token']; ?>">
            <label class="labelstyle" for="name" accesskey="U">Name</label>
            <input name="name" type="text" id="name" tabindex="1" autofocus required="required" />

            <label class="labelstyle" for="email" accesskey="E">Email</label>
            <input name="email" type="email" id="email" tabindex="2" required="required" />

            <label class="labelstyle" for="phone" accesskey="P" >Phone <small>(optional)</small></label>
            <input name="phone" type="tel" id="phone" tabindex="3">

            <label class="labelstyle" for="web" accesskey="W">Website <small>(optional)</small></label>
            <input name="website" type="text"  id="web" tabindex="4">

            <div id="radio-toolbar">
                <input type="radio" id="radioMessage" name="reason" value="message" checked>
                <label for="radioMessage">message</label>

                <input type="radio" id="radioOrder" name="reason" value="order">
                <label for="radioOrder">order</label>

                <input type="radio" id="radioStatus" name="reason" value="status">
                <label for="radioStatus">status</label> 
            </div>
            <p>&nbsp;</p>
            <label class="textareaLabel" for="comments">Comments</label>
            <textarea name="comments" id="comments" spellcheck="true" tabindex="6" required="required"></textarea> 
            <div class="g-recaptcha" data-sitekey="6LdXNpAUAAAAAMwtslAEqbi9CU3sviuv2imYbQfe"></div>
            <input type="submit" name="submit" value="submit" tabindex="7">
        </fieldset>
    </form>

</section>

<?php
include '../private/includes/footer.inc.php';

and here’s the nut & bolts of my Class that is basically written in procedural form.

/* 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'];
$email_from = $data['email'];
$subject = $data['reason'] . ' email address ' . $data['email'];
$comments = $data['phone'] . ' ' . $data['website'] . ' ' . $data['comments'];

/*
 * Email Address message is going to
 */
$message->setTo([
   '[email protected]' => 'John Smith //  Email : Name
]);

$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;
}

I don’t use HTML, but swiftmailer documentation gives all the information on how to do it and it is relatively easy to setup.

I am not plugging my website as I just want to show that it does actually work -> https://www.miniaturephotographer.com/contact.php

Though I need to polish it up some more, but I have been busy working on other parts of my website.

1 Like

The posted code contains a number of syntax/logic mistakes and doesn’t even run, which should have been producing php syntax errors, if your php error related settings are set up to display all php errors.

To get php to help you, start by finding the php.ini that php is using and set error_reporting to E_ALL and set display_errors to ON.

Next, except perhaps during your testing, these emails are not being sent from the email address that someone enters in the form. They are being sent from the mail server at your web hosting and the From: mail header must be an email address that corresponds to your mail server. You can put the submitted email address into a Reply-to: mail header.

1 Like

Thanks for the direction this is my first time writing something like this in PHP, so I’ll go back and debug. Thanks for the advice.

I’ll look into php mailer instead, but now I just want to fix this because it gave me trouble I think it will be a good learning experience. Thanks for the proof of concept showing me how it works I’ll check out your site for sure I think its equal exchange for the knowledge haha. Inspiration from other people is always welcome. Have a good day.

Sponsor our Newsletter | Privacy Policy | Terms of Service