0

I have been trying to create a contact form where anyone can send an email to the website host. I have tried using PHPMailer with the Gmail SMTP server. I have also installed composer as suggested in some posts. Nothing seems to be working. Here is the code:

<?php
require 'PHPMailerAutoload.php';

//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost', 'root', '', 'perfectcup');

//Output any connection error
if ($mysqli->connect_error) {
    die('Error : (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}

$fname = mysqli_real_escape_string($mysqli, $_POST['fname']);
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
$message= mysqli_real_escape_string($mysqli, $_POST['message']);

$email2 = "";
$subject = "Test Message";

if (strlen($fname) > 50) {
    echo 'fname_long';

} elseif (strlen($fname) < 2) {
    echo 'fname_short';

} elseif (strlen($email) > 50) {
    echo 'email_long';

} elseif (strlen($email) < 2) {
    echo 'email_short';

} elseif (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    echo 'eformat';

} elseif (strlen($message) > 500) {
    echo 'message_long';

} elseif (strlen($message) < 3) {
    echo 'message_short';

} else {
    
     //MAILER
    require '/phpmailer/PHPMailerAutoload.php';

    $mail = new PHPMailer();
    error_reporting(E_ALL);
    ini_set('display_errors','1');
    //$mail->SMTPDebug = 3;                               // Enable verbose debug output

    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.mail.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'youremail@gmail.com';                 // SMTP username
    $mail->Password = 'passowrd';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 465;                                    // TCP port to connect to

    $mail->AddReplyTo($email);
    $mail->From = $email2;
    $mail->FromName = $fname;
   
    $mail->SMTPDebug=2;
    $mail->isHTML(true);                                  // Set email format to HTML

    $mail->Subject = $subject;
    $mail->Body = $message;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    if (!$mail->send()) {
        echo 'Message could not be sent.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'true';
    }
}
?>

This is the code that I have used for the contact form:

<script src="js/jquery.js"></script>
    
        <script type="text/javascript">
        $(document).ready(function () {

            $("#contact").click(function () {

                fname = $("#fname").val();
                email = $("#email").val();
                message = $("#message").val();

                $.ajax({
                    type: "POST",
                    url: "sendmsg.php",
                    data: "fname=" + fname + "&email=" + email + "&message=" + message,
                    success: function (html) {
                        if (html == 'true') {

                            $("#add_err2").html('<div class="alert alert-success"> \
                                                 <strong>Message Sent!</strong> \ \
                                                 </div>');

                        } else if (html == 'fname_long') {
                            $("#add_err2").html('<div class="alert alert-danger"> \
                                                 <strong>First Name</strong> must cannot exceed 50 characters. \ \
                                                 </div>');
                        
                        } else if (html == 'fname_short') {
                            $("#add_err2").html('<div class="alert alert-danger"> \
                                                 <strong>First Name</strong> must exceed 2 characters. \ \
                                                 </div>');
                                                 
                        } else if (html == 'email_long') {
                            $("#add_err2").html('<div class="alert alert-danger"> \
                                                 <strong>Email</strong> must cannot exceed 50 characters. \ \
                                                 </div>');
                        
                        } else if (html == 'email_short') {
                            $("#add_err2").html('<div class="alert alert-danger"> \
                                                 <strong>Email</strong> must exceed 2 characters. \ \
                                                 </div>');
                                                 
                        } else if (html == 'eformat') {
                            $("#add_err2").html('<div class="alert alert-danger"> \
                                                 <strong>Email</strong> format incorrect. \ \
                                                 </div>');
                                                 
                        } else if (html == 'message_long') {
                            $("#add_err2").html('<div class="alert alert-danger"> \
                                                 <strong>Message</strong> must cannot exceed 50 characters. \ \
                                                 </div>');
                        
                        } else if (html == 'message_short') {
                            $("#add_err2").html('<div class="alert alert-danger"> \
                                                 <strong>Message</strong> must exceed 2 characters. \ \
                                                 </div>');


                        } else {
                            $("#add_err2").html('<div class="alert alert-danger"> \
                                                 <strong>Error</strong> processing request. Please try again. \ \
                                                 </div>');
                        }
                    },
                    beforeSend: function () {
                        $("#add_err2").html("loading...");
                    }
                });
                return false;
            });
        });
    </script>
</head>

<body>

    <div class="brand">The Perfect Cup</div>
    <div class="address-bar">3481 Melrose Place | Beverly Hills, CA 90210 | 123.456.7890</div>

    <!-- Navigation -->
    <?php require_once 'nav.php'; ?>

    <div class="container">

        <div class="row">
            <div class="box">
                <div class="col-lg-12">
                    <hr>
                    <h2 class="intro-text text-center">Contact
                        <strong>The Perfect Cup</strong>
                    </h2>
                    <hr>
                </div>
                <div class="col-md-8">
                <iframe src="https://www.google.com/maps/embed?pb=!1m16!1m12!1m3!1d105743.04700852593!2d-118.43314319603537!3d34.08309263846107!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!2m1!1s3481%20Melrose%20Place%20Beverly%20Hills%2C%20CA%2090210!5e0!3m2!1sen!2sus!4v1624811422150!5m2!1sen!2sus" width="100%" height="400" style="border:0;" allowfullscreen="" loading="lazy"></iframe>
                </div>
                <div class="col-md-4">
                    <p>Phone:
                        <strong>123.456.7890</strong>
                    </p>
                    <p>Email:
                        <strong><a href="mailto:info@theperfectcup.com">info@theperfectcup.com</a></strong>
                    </p>
                    <p>Address:
                        <strong>3481 Melrose Place
                            <br>Beverly Hills, CA 90210</strong>
                    </p>
                </div>
                <div class="clearfix"></div>
            </div>
        </div>

        <div class="row">
            <div class="box">
                <div class="col-lg-12">
                    <hr>
                    <h2 class="intro-text text-center">Contact
                        <strong>form</strong>
                    </h2>
                    <hr>
                    <div id="add_err2"></div>
                    <form role="form">
                        <div class="row">
                            <div class="form-group col-lg-4">
                                <label>Name</label>
                                <input type="text" id="fname" name="fname" maxlength="25" class="form-control">
                            </div>
                            <div class="form-group col-lg-4">
                                <label>Email Address</label>
                                <input type="email" id="email" name="email" maxlength="25" class="form-control">
                            </div>
                            <div class="clearfix"></div>
                            <div class="form-group col-lg-12">
                                <label>Message</label>
                                <textarea class="form-control" rows="6"></textarea>
                            </div>
                            <div class="form-group col-lg-12">
                            <button type="submit"  id="contact" class="btn btn-default">Submit</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

    </div>
    <!-- /.container -->
    <footer>
        <div class="container">
            <div class="row">
                <div class="col-lg-12 text-center">
                    <p>Copyright &copy;The Perfect Cup 2020</p>
                </div>
            </div>
        </div>
    </footer>
    
    <!-- Bootstrap Core JavaScript -->
    <script src="js/bootstrap.min.js"></script>

</body>
</html>
Deadvilla
  • 1
  • 1
  • Why do you use `mysqli_real_escape_string`? Remove it – Dharman Jul 13 '21 at 15:31
  • [Read the troubleshooting guide](https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting). You're using a very old version that's likely vulnerable to attack. Your encryption config is wrong. You might have installed composer, but you're not using it. Your from address is empty. Your `Host` value is wrong for gmail. Read the guide, base your code on the examples provided. – Synchro Jul 13 '21 at 16:02
  • @Dharman I used mysqli_real_escape_string to avoid any SQL injection attack. I am not completely sure, I rade on some article that this syntax help avoid SQL injection., – Deadvilla Jul 14 '21 at 11:34
  • Please don't use it. Use parameterized prepared statements. Read https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement – Dharman Jul 14 '21 at 11:35
  • @Synchro sir, Thank you for your help, I am a beginner, I used the PHPMailer from https://github.com/PHPMailer/PHPMailer and added it to the file where my project is. I am using Wampserver64 and have added my project to the www file in the server. Do I have to install the composer to the same file. – Deadvilla Jul 14 '21 at 11:38
  • @Dharman I really appreciate your support, Can you help me understand more, I went through the article but I am having a hard time understanding. – Deadvilla Jul 14 '21 at 11:56
  • 1
    Yes, escaping is a way to avoid SQL injection, but here you are using it in non-SQL context, so it's doing nothing useful, and may corrupt the strings for the purpose you do want to use them for. Composer isn't something you need for its own sake, it's a tool you use to fetch and load other packages and their dependencies. – Synchro Jul 14 '21 at 12:01

0 Answers0