Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Build a Basic PHP Website (2018) Adding a Basic Form Utilizing Object Properties and Methods

Siraj Khan
Siraj Khan
3,451 Points

Whats wrong with my code.? Please help

The suggest.php page does not loads at all. Please help what am I missing.

<?php

//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
require 'vendor/phpmailer/src/PHPmailer.php';
require 'vendor/phpmailer/src/Exception.php';


if ($_SERVER["REQUEST_METHOD"] == "POST") {
      $name = trim(filter_input(INPUT_POST, "name", FILTER_SANITIZE_STRING));
      $email = trim(filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL))
      $details = trim(filter_input(INPUT_POST, "details", FILTER_SANITIZE_SPECIAL_CHARS))

      if ($name == "" || $email == "" || $details == "") {
        echo "Please fill in the required fields: Name, Email and Details";
        exit;
      }


      if ($_POST["address" != ""]) {
        echo "Bad form input";
        exit;
      }

      require("inc/phpmailer/class.phpmailer.php");

      $mail = new PHPMailer;

      if (!$mail::ValidateAddress($email)) {
        echo "Invalid Email Address";
        exit;
      }


      $email_body = "";
      $email_body .= "Name " . $name . "\n";
      $email_body .= "Email " . $email . "\n";
      $email_body .= "Details " . $details . "\n";

       // TO DO: Send email


       //It's important not to use the submitter's address as the from address as it's forgery,
       //which will cause your messages to fail SPF checks.
       //Use an address in your own domain as the from address, put the submitter's address in a reply-to
       $mail->setFrom($email, $name);
       $mail->addAddress('siraj@safranpvt.com', 'Siraj Khan'); // Add a recipient

       $mail->isHTML(false);                                  // Set email format to HTML

       $mail->Subject = 'Personal Media Library suggestion from' . $name;
       $mail->Body = $email_body;

       if (!$mail->send()) {
           echo "Message could not be sent.";
           echo "Mailer Error: " . $mail->ErrorInfo;
           exit;
       }

       header("location:suggest.php?status=thanks");
}


$pageTitle = "Suggest a media Item";
$section = "suggest";

include('inc/header.php') ; ?>


<div class="section page">
  <div class="wrapper">
    <h1>Suggest a Media Item</h1>

    <?php if (isset($_GET["status"]) && $_GET["status"] == "thanks") {
      echo "<p>Thanks for the email. I will check out your suggestion shortly!</p>";
    } else { ?>

    <p>If you think there is something I am missing, let me know.! Complete the form to send me an email.</p>

    <form method="post" action="suggest.php">

      <table>
        <tr>
          <th><label for="name">Name</label></th>
          <td><input type="text" id="name" name="name"></td>
        </tr>
        <tr>
          <th><label for="email">Email</label></th>
          <td><input type="text" id="email" name="email"></td>
        </tr>
        <tr>
          <th><label for="details">Suggest Item Details</label></th>
          <td><textarea name="details" id="details"></textarea></td>
        </tr>
        <tr style="display:none">
          <th><label for="address">Address</label></th>
          <td><input type="text" id="address" name="address"/>
          <p>Please leave this field blank</p></td>
        </tr>

      </table>

      <input type="submit" value="Send" />

    </form>

  <?php } ?>

  </div>

</div>

<?php include('inc/footer.php'); ?>

4 Answers

mttg
mttg
2,421 Points

try this

<?php

//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/src/Exception.php';
require 'vendor/phpmailer/src/SMTP.php';


if ($_SERVER["REQUEST_METHOD"] == "POST") {
      $name = trim(filter_input(INPUT_POST, "name", FILTER_SANITIZE_STRING));
      $email = trim(filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL));
      $details = trim(filter_input(INPUT_POST, "details", FILTER_SANITIZE_SPECIAL_CHARS));

      if ($name == "" || $email == "" || $details == "") {
        echo "Please fill in the required fields: Name, Email and Details";
        exit;
      }


      if (@$_POST["address" != ""]) {
        echo "Bad form input";
        exit;
      }


      if (!PHPMailer::ValidateAddress($email)) {
        echo "Invalid Email Address";
        exit;
      }


      $email_body = "";
      $email_body .= "Name " . $name . "\n";
      $email_body .= "Email " . $email . "\n";
      $email_body .= "Details " . $details . "\n";

       // TO DO: Send email
      $mail = new PHPMailer;


      //Tell PHPMailer to use SMTP
      $mail->isSMTP();
      //Enable SMTP debugging
      // 0 = off (for production use)
      // 1 = client messages
      // 2 = client and server messages
      $mail->SMTPDebug = 2;
      //Set the hostname of the mail server
      $mail->Host = 'smtp.gmail.com';
      // use
      // $mail->Host = gethostbyname('smtp.gmail.com');
      // if your network does not support SMTP over IPv6
      //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
      $mail->Port = 587;
      //Set the encryption system to use - ssl (deprecated) or tls
      $mail->SMTPSecure = 'tls';
      //Whether to use SMTP authentication
      $mail->SMTPAuth = true;
      //Username to use for SMTP authentication - use full email address for gmail
      $mail->Username = "sirajdevelopment123@gmail.com";
      //Password to use for SMTP authentication
      $mail->Password = "your password";

       //It's important not to use the submitter's address as the from address as it's forgery,
       //which will cause your messages to fail SPF checks.
       //Use an address in your own domain as the from address, put the submitter's address in a reply-to
       $mail->setFrom($email, $name);
       $mail->addAddress('sirajdevelopment123@gmail.com', 'Siraj Khan'); // Add a recipient

       $mail->isHTML(false);                                  // Set email format to HTML

       $mail->Subject = 'Personal Media Library suggestion from' . $name;
       $mail->Body = $email_body;

       if (!$mail->send()) {
           echo "Message could not be sent.";
           echo "Mailer Error: " . $mail->ErrorInfo;
           exit;
       }

       header("location:test.php?status=thanks");
}


$pageTitle = "Suggest a media Item";
$section = "suggest";

include('inc/header.php') ; ?>


<div class="section page">
  <div class="wrapper">
    <h1>Suggest a Media Item</h1>

    <?php if (isset($_GET["status"]) && $_GET["status"] == "thanks") {
      echo "<p>Thanks for the email. I will check out your suggestion shortly!</p>";
    } else { ?>

    <p>If you think there is something I am missing, let me know.! Complete the form to send me an email.</p>

    <form method="post" action="test.php">

      <table>
        <tr>
          <th><label for="name">Name</label></th>
          <td><input type="text" id="name" name="name"></td>
        </tr>
        <tr>
          <th><label for="email">Email</label></th>
          <td><input type="text" id="email" name="email"></td>
        </tr>
        <tr>
          <th><label for="details">Suggest Item Details</label></th>
          <td><textarea name="details" id="details"></textarea></td>
        </tr>
        <tr style="display:none">
          <th><label for="address">Address</label></th>
          <td><input type="text" id="address" name="address"/>
          <p>Please leave this field blank</p></td>
        </tr>

      </table>

      <input type="submit" value="Send" />

    </form>

  <?php } ?>

  </div>

</div>

<?php include('inc/footer.php'); ?>
Siraj Khan
Siraj Khan
3,451 Points

Still not working, sir.! :(

Siraj Khan
Siraj Khan
3,451 Points

It worked. Thank you so much mate.!

mttg
mttg
2,421 Points

Hi,

you must type the ";" on line 11 and 12. And you must also capitalize the "M" on line 5 at PHPMailer.php

Siraj Khan
Siraj Khan
3,451 Points

Thanks a lot mate. The problem now is that I can't send the email; Can you please help me out in that also..? Thank you. sirajdevelopment123@gmail.com is the account where I got my password ; for apps with access to your account.

<?php

//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
require 'vendor/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/src/Exception.php';
require 'vendor/phpmailer/src/SMTP.php';


if ($_SERVER["REQUEST_METHOD"] == "POST") {
      $name = trim(filter_input(INPUT_POST, "name", FILTER_SANITIZE_STRING));
      $email = trim(filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL));
      $details = trim(filter_input(INPUT_POST, "details", FILTER_SANITIZE_SPECIAL_CHARS));

      if ($name == "" || $email == "" || $details == "") {
        echo "Please fill in the required fields: Name, Email and Details";
        exit;
      }


      if ($_POST["address" != ""]) {
        echo "Bad form input";
        exit;
      }

      require("inc/phpmailer/class.phpmailer.php");


      if (!$mail::ValidateAddress($email)) {
        echo "Invalid Email Address";
        exit;
      }


      $email_body = "";
      $email_body .= "Name " . $name . "\n";
      $email_body .= "Email " . $email . "\n";
      $email_body .= "Details " . $details . "\n";

       // TO DO: Send email
      $mail = new PHPMailer;


      //Tell PHPMailer to use SMTP
      $mail->isSMTP();
      //Enable SMTP debugging
      // 0 = off (for production use)
      // 1 = client messages
      // 2 = client and server messages
      $mail->SMTPDebug = 2;
      //Set the hostname of the mail server
      $mail->Host = 'smtp.gmail.com';
      // use
      // $mail->Host = gethostbyname('smtp.gmail.com');
      // if your network does not support SMTP over IPv6
      //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
      $mail->Port = 587;
      //Set the encryption system to use - ssl (deprecated) or tls
      $mail->SMTPSecure = 'tls';
      //Whether to use SMTP authentication
      $mail->SMTPAuth = true;
      //Username to use for SMTP authentication - use full email address for gmail
      $mail->Username = "sirajdevelopment123@gmail.com";
      //Password to use for SMTP authentication
      $mail->Password = "***************";

       //It's important not to use the submitter's address as the from address as it's forgery,
       //which will cause your messages to fail SPF checks.
       //Use an address in your own domain as the from address, put the submitter's address in a reply-to
       $mail->setFrom($email, $name);
       $mail->addAddress('sirajdevelopment123@gmail.com', 'Siraj Khan'); // Add a recipient

       $mail->isHTML(false);                                  // Set email format to HTML

       $mail->Subject = 'Personal Media Library suggestion from' . $name;
       $mail->Body = $email_body;

       if (!$mail->send()) {
           echo "Message could not be sent.";
           echo "Mailer Error: " . $mail->ErrorInfo;
           exit;
       }

       header("location:suggest.php?status=thanks");
}


$pageTitle = "Suggest a media Item";
$section = "suggest";

include('inc/header.php') ; ?>


<div class="section page">
  <div class="wrapper">
    <h1>Suggest a Media Item</h1>

    <?php if (isset($_GET["status"]) && $_GET["status"] == "thanks") {
      echo "<p>Thanks for the email. I will check out your suggestion shortly!</p>";
    } else { ?>

    <p>If you think there is something I am missing, let me know.! Complete the form to send me an email.</p>

    <form method="post" action="suggest.php">

      <table>
        <tr>
          <th><label for="name">Name</label></th>
          <td><input type="text" id="name" name="name"></td>
        </tr>
        <tr>
          <th><label for="email">Email</label></th>
          <td><input type="text" id="email" name="email"></td>
        </tr>
        <tr>
          <th><label for="details">Suggest Item Details</label></th>
          <td><textarea name="details" id="details"></textarea></td>
        </tr>
        <tr style="display:none">
          <th><label for="address">Address</label></th>
          <td><input type="text" id="address" name="address"/>
          <p>Please leave this field blank</p></td>
        </tr>

      </table>

      <input type="submit" value="Send" />

    </form>

  <?php } ?>

  </div>

</div>

<?php include('inc/footer.php'); ?>
Siraj Khan
Siraj Khan
3,451 Points

Can you please explain, why did we have to make those changes.? I want to understand so that i know the concept.

mttg
mttg
2,421 Points

Hi,

at

$mail->Password = "***************";

You don't use your normal gmail password, you must set your 2 factor authentication. Then you can create an app password that you type there.

Siraj Khan
Siraj Khan
3,451 Points

Yes, I did that. It still does not works. I am using local server MAMP.

mttg
mttg
2,421 Points

Sure, many things are not necessary like the "@_POST" and the "use PHPMailer\PHPMailer\Exception;" I put them in for error handling, the @ suppresses error messages.

Your

      require("inc/phpmailer/class.phpmailer.php");

is not needed, we required it at the beginning.

In this line

      if (!$mail::ValidateAddress($email)) {
        echo "Invalid Email Address";
        exit;
      }

you first got the wrong variable, it's $email not $mail. but it wouldn't work anyway. PHPMailer has a build in function for this task (Email validation) So I changed it to

      if (!PHPMailer::ValidateAddress($email)) {
        echo "Invalid Email Address";
        exit;
      }

I hope you understand. Im not really good in explaining and English is not my first language.