Jump to content

Sending validated PHP form via SMTP


Patwan

Recommended Posts

Hey guys, am a newbie in PHP pprogramming. I have created a Contact form on my website which validates through Regex(preg_match function) but can`t send the email to my Gmail account. I have already enabled "less secure apps" in my Gmail account settings. I am using PHPMailer class to send the messages via XAMPP sever. Kindly assist me in rectifying any error in the code below.

~ Kind regards

 

 

<?php

//initialize variables and set to empty values

$name = $phone = $email = $business= " ";
$nameErr = $phoneErr = $emailErr = $businessErr = " ";


if ($_SERVER["REQUEST_METHOD"] == "POST")
{$valid = true;

//check if name contains letters and white-space
if (empty($_POST["name"]))
{$nameErr = "Please fill out this field"; $valid =false;}
else {$name = test_input($_POST["name"]);

if (!preg_match("/^[a-zA-Z ,.-]*$/", $name))
{$nameErr = "*Only Letters and white-spaces are allowed*";}}

//check if phone contains numbers
if (empty($_POST["phone"]))
{$phoneErr = "Please fill out this field"; $valid =false;}
else {$phone = test_input ($_POST["phone"]);

if (!preg_match("/^[0-9 ,+.-]*$/", $phone))
{$phoneErr = "*Only numbers are allowed*";}}

//check if email is valid
if (empty($_POST["email"]))
{$emailErr = "Please fill out this field"; $valid =false;}
else {$email = test_input ($_POST["email"]);

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{$emailErr = "*Invalid email address*";}}


//check if business field is valid
if (empty($_POST["business"]))
{$businessErr = "Please fill out this field"; $valid =false;}
else {$business = test_input($_POST["business"]);

if (!preg_match("/^[a-zA-Z-.+:; ]*$/", $business))
{$businessErr= "*Only letters and spaces are allowed*";}}


require ("PHPMailer_5.2.4/class.phpmailer.php"); //including phpmailer class

$mail = new PHPMailer();

$mail->IsSMTP(); // set mailer to use SMTP
$mail->SMTPDebug =0;
$mail->Host = "smtp.gmail.com"; // specify main and backup server
$mail->SMTPSecure = "ssl"; // Connect using a TLS connection
$mail->Port = 465; //Gmail SMTP port
$mail->SMTPAuth = true; // turn on SMTP authorization
$mail->Username = "my gmail account"; // SMTP username
$mail->Password = " ************** "; // SMTP password

$mail->From = $email; //email of sender
$mail->FromName = $name; //name of the sender
$mail->AddAddress("my gmail account", "Patwan"); //email address of recepient and name
$mail->AddAddress("my gmail account", "Test email"); // name is optional
$mail->AddReplyTo($_POST["email"], $_POST["name"]); //Address to which recepient will reply

$mail->WordWrap = 100; // set word wrap to 100 characters
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "Contact Form"; //subject of email

$mail->Body = "Name: " .$_POST['name'] . "<br>Phone: " . $_POST['phone'] . "<br>Email: " . $_POST['email'] .
"<br>Business: " . $_POST['business'] ;

if($valid){
if(!$mail->Send())
{
echo 'Form could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
else {header('Location:thank_you.html');}}
}

function test_input($data)
{$data = trim($data);
$data = stripslashes ($data);
$data = htmlspecialchars ($data);
return $data;
}

?>


<!DOCTYPE html>
<html>
<html lang= "en-US">

<head>
<meta name= "robots" content= "noindex, nofollow">
<meta charset="UTF-8">
<meta name= "author" content= "Kelly James">
<link href= "style.css" rel= "stylesheet" type= "text/css">
<title> Contact form </title>
</head>

<body>

<image src= "images/logo.gif" border= "0" width= "240px" height="160px">

<br>
<div class="form">

<form method= "post" action= "<?php echo htmlspecialchars ($_SERVER["PHP_SELF"]);?>" >

<h4 id="h4form"> Please fill the form below to kick start your project. <br> <br> <font color="red"> *required field </font> </h4>

<br> What is your name? <input type= "text" class= "input" name= "name" placeholder= "e.g Nelson Mandela" value="<?php echo $name;?>" required> <span class= "error"> * <br> <?php echo $nameErr;?> </span>

<br> <br>What is your phone number? <input type= "text" class= "input" name= "phone" value="<?php echo $phone;?>" placeholder= "e.g 0722222222" required> <span class= "error"> * <br> <?php echo $phoneErr;?> </span>

<br> <br> What is your email address? <input type= "email" class= "input" name= "email" placeholder= "will not be published" value="<?php echo $email;?>" required> <span class= "error"> * <br> <?php echo $emailErr;?> </span>

<br> <br> What is the name of your business or institution? <input type= "text" class= "input" name="business" placeholder= "e.g Microsoft Corporation" value= "<?php echo $business;?>" required> <span class= "error"> * <br> <?php echo $businessErr;?> </span>

 

<br> <br> <button class="submit" type= "submit" value= "Submit"> Submit Form </button>

 

</form>
</div>
</body>
</html>

 

 

Link to comment
Share on other sites

Pardon me, I forgot to tell you that it displays errors when there is wrong user input after pressing Submit button. But if there is correct input it only displays them on the Form fields without redirecting to the next page or sending a mail in my inbox. Could there be a problem in my coding?

Link to comment
Share on other sites

I would start by adding this to the top of your code:

 

ini_set('display_errors', 1);
error_reporting(E_ALL);
You should also format your code a little better so that it's easier to read, it's always better to make code as readable as possible instead of trying to use as few lines as possible. Your code won't try to send the email or redirect if $valid is set to false, so you may want to add some code to print messages about what it's doing so that you can see if $valid is set to false and why.
Link to comment
Share on other sites

I'm just suggesting to add some code to output some messages so you can see what it's doing, e.g.:

 

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $valid = true;

  //check if name contains letters and white-space
  if (empty($_POST["name"])) {
    $nameErr = "Please fill out this field";  
    $valid = false;
    echo 'name is empty<br>';
  }
  else {
    $name = test_input($_POST["name"]);

    if (!preg_match("/^[a-zA-Z ,.-]*$/", $name))
    {
      $nameErr = "*Only Letters and white-spaces are allowed*";
      echo 'name did not pass regexp<br>';
    }
    else {
      echo 'name is valid<br>';
    }
  }
Make sure to add the lines I posted above to the top of your code so that you know if there are any errors.
Link to comment
Share on other sites

Hey, I adjusted the following code as you advised me:

 

<?php

//initialize variables and set to empty values

$name = $phone = $email = $business= " ";
$nameErr = $phoneErr = $emailErr = $businessErr = " ";

 

ini_set('display_errors', 1);
error_reporting(E_ALL);


if ($_SERVER["REQUEST_METHOD"] == "POST")
{$valid = true;

//check if name contains letters and white-space
if (empty($_POST["name"]))
{$nameErr = "Please fill out this field"; $valid =false; echo 'name is empty<br>'; }
else {$name = test_input($_POST["name"]);

if (!preg_match("/^[a-zA-Z ,.-]*$/", $name))
{$nameErr = "*Only Letters and white-spaces are allowed*"; echo 'name did not pass regexp<br>';} else{echo'name is valid<br>';}}

/check if phone contains numbers
if (empty($_POST["phone"]))
{$phoneErr = "Please fill out this field"; $valid =false; echo'phone is empty<br>';}
else {$phone = test_input ($_POST["phone"]);

if (!preg_match("/^[0-9 ,+.-]*$/", $phone))
{$phoneErr = "*Only numbers are allowed*"; echo 'phone did not pass regexp<br>';} else{echo' phone is valid<br>'; }}

//check if email is valid
if (empty($_POST["email"]))
{$emailErr = "Please fill out this field"; $valid =false; echo'email is empty<br>';}
else {$email = test_input ($_POST["email"]);

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{$emailErr = "*Invalid email address*"; echo 'email did not pass regexp<br>';} else{echo'email is valid<br>';}}


//check if business field is valid
if (empty($_POST["business"]))
{$businessErr = "Please fill out this field"; $valid =false; echo 'business is empty<br>'; }
else {$business = test_input($_POST["business"]);

if (!preg_match("/^[a-zA-Z-.+:; ]*$/", $business))
{$businessErr= "*Only letters and spaces are allowed*"; echo 'business did not pass regexp<br>';} else {echo 'business is valid<br>';}}


require ("PHPMailer_5.2.4/class.phpmailer.php"); //including phpmailer class

$mail = new PHPMailer();

$mail->IsSMTP(); // set mailer to use SMTP
$mail->SMTPDebug =0;
$mail->Host = "smtp.gmail.com"; // specify main and backup server
$mail->SMTPSecure = "ssl"; // Connect using a TLS connection
$mail->Port = 465; //Gmail SMTP port
$mail->SMTPAuth = true; // turn on SMTP authorization
$mail->Username = "my gmail account"; // SMTP username
$mail->Password = " ************** "; // SMTP password

$mail->From = $email; //email of sender
$mail->FromName = $name; //name of the sender
$mail->AddAddress("my gmail account", "Patwan"); //email address of recepient and name
$mail->AddAddress("my gmail account", "Test email"); // name is optional
$mail->AddReplyTo($_POST["email"], $_POST["name"]); //Address to which recepient will reply

$mail->WordWrap = 100; // set word wrap to 100 characters
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "Contact Form"; //subject of email

$mail->Body = "Name: " .$_POST['name'] . "<br>Phone: " . $_POST['phone'] . "<br>Email: " . $_POST['email'] .
"<br>Business: " . $_POST['business'] ;

if($valid){
if(!$mail->Send())
{
echo 'Form could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
else {header('Location:thank_you.html');}}
}

function test_input($data)
{$data = trim($data);
$data = stripslashes ($data);
$data = htmlspecialchars ($data);
return $data;
}

?>

Link to comment
Share on other sites

When there is correct user input, it displays at the top of the form "name is valid, phone is valid, email is valid, business is valid"

 

When there is incorrect input, it validates properly & displays error messages on the form and at the top of the form " name did not pass regexp " etc.

 

But the problem still persists, it doesnt redirect to the next page or send email?

Link to comment
Share on other sites

It won't redirect because the test code that is used in else condition that produces text and html prevents it from working, as it should run before any such output.

 

So once the code produces the correct response, it should be removed or commented out.

Link to comment
Share on other sites

Which else condition are you talking about. Could you expound further using examples in coding, so that I can understand. My aim is that the form:validates, sends an email to my Gmail account if there is correct user input & then redirect to another page called "thank_you.html".

 

In the code above, the form validates properly using Regexp, but fails to send an email to me, then later redirect to "thank_you.html" page ?

 

Any help please?

Link to comment
Share on other sites

He's pointing out that if you output those test messages, then the page will not redirect because of that.

 

If I search for PHPmailer and GMail I find this, I'm not sure if GMail requires TLS on port 587, but it's one thing to check.

 

http://phpmailer.worxware.com/?pg=examplebgmail

https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps

Link to comment
Share on other sites

Hey, I have configured C:\xampp\php\php.ini and C:\xampp\sendmail\sendmail.ini files in XAMPP server.

In C:\xampp\php\php.ini file, I found extension=php_openssl.dll and removed the semicolon from the beginninng of the line.

I also changed the following bold lines in [mail function]:



[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP=smtp.gmail.com
; http://php.net/smtp-port
smtp_port=587

; For Win32 only.
; http://php.net/sendmail-from
sendmail_from =my-gmail-id@gmail.com

; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path ="\"C:\xampp\sendmail\sendmail.exe\" -t"

I then opened C:\xampp\sendmail\sendmail.ini and changed the following lines writen in bold

 

[sendmail]

; you must change mail.mydomain.com to your smtp server,
; or to IIS's "pickup" directory. (generally C:\Inetpub\mailroot\Pickup)
; emails delivered via IIS's pickup directory cause sendmail to
; run quicker, but you won't get error messages back to the calling
; application.

smtp_server=smtp.gmail.com

; smtp port (normally 25)

smtp_port=587

; SMTPS (SSL) support
; auto = use SSL for port 465, otherwise try to use TLS
; ssl = alway use SSL
; tls = always use TLS
; none = never try to use SSL

smtp_ssl=auto

; the default domain for this server will be read from the registry
; this will be appended to email addresses when one isn't provided
; if you want to override the value in the registry, uncomment and modify

;default_domain=mydomain.com

; log smtp errors to error.log (defaults to same directory as sendmail.exe)
; uncomment to enable logging

error_logfile=error.log

; create debug log as debug.log (defaults to same directory as sendmail.exe)
; uncomment to enable debugging

;debug_logfile=debug.log

; if your smtp server requires authentication, modify the following two lines

auth_username=my-gmail-id@gmail.com
auth_password=**************

Link to comment
Share on other sites

After configuration of the code above, I restarted my XAMPP server but the problem still persists. Could there be any other file I need to configure, cause its` driving me nuts & am running out of time

 

~ Any advice will be highly appreciated?

Link to comment
Share on other sites

Yeah, I tested the PHPMailer before, it worked fine, by then it could send emails before passing user input through validation. But after I added the $valid functions in the coding to help in checking validation before sending any mail, it stopped sending mails to my inbox. I don't know what went wrong after adding $valid functions to the code?

Link to comment
Share on other sites

This

 $mail->From = $email;                         //email of sender

shows two different versions (1) as above and also (2)

 $mail->SetFrom = $email;                         //email of sender

If I were you I'd get the test example to work, then add each validation checking code, one at a time to identify where/what causes it to fail.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...