简体   繁体   中英

PHP Contact Form don't respond properly

I'm new to PHP and I've got issue in my contact form. When I press "Submit" in my form it skips (somewhere, I don't know where and why it happens) to other site, and conditions are not checked by the php code. What's more, you can type wrong answer in "human recognizer" and it will still send and email. I was looking for som bad declarations or wrong syntax, but all seems to be good. I assume that also my contact.php responds properly if it sends an email (but without checking conditions). I don't know if it's connected but my modal window in it also doesn't want to close (but on the other site the same code works fine, when there is other form withoud "action=contact.php" field).

My main head.php:

<!--HEAD-->
<head>
    <title>X</title>

<!--META-->
    <meta http-equiv="Content-Type" content="text/html"; charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="author" content="SitePoint">

<!--CSS-->
    <link id="theme" rel="stylesheet" href="css/light.css">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">


<!-- Font Awesome -->
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

</head>
<!--END OF HEAD-->
    <body>
        <script src="https://code.jquery.com/jquery-3.2.1.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
        <script src="js/dropdown.js"></script>
        <script src="js/scrolling-nav.js"></script>
        <script src="js/theme-switch.js"></script>
        <script src="js/nav-position.js"></script>

            <nav id="mainNav">
                <bar>
                    <i id="hamburger" class="fa fa-bars" aria-hidden="true"></i>
                </bar>
                <ul id="menu">
                    <li><a href="#main">Main</a></li>
                    <li><a href="#generator">Generator</a></li>
                    <li><a href="#about">About</a></li>
                    <li><a href="#contact">Contact</a></li>
                </ul>
            </nav>

        <section id = "main" >
        <div class = "content">
        <h1>Hello!</h1>
        <p>:)</p>
        </div></section>

        <section id = "generator">
        <div class = "content">
        <h1>Generator</h1>
          <form id="generator-form" ="form-horizontal" role="form" method="post" action="generator.php">
                <div class="form-group">
                    <label for="name" class="col-sm-2 control-label">Name</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
                        <?php echo "<p class='text-danger'>$errName</p>";?>
                    </div>
                </div>
        <div class="form-group">
                    <label for="idCardNumber" class="col-sm-2 control-label">Name</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="idCardNumber" name="idCardNumber" placeholder="Student ID Card Number" value="<?php echo htmlspecialchars($_POST['name']); ?>">
                        <?php echo "<p class='text-danger'>$errName</p>";?>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-10 col-sm-offset-2">
                        <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-10 col-sm-offset-2">
                        <?php echo $result; ?>
                    </div>
                </div>
            </form> 
        </div></section>

        <section id = "about">
        <div class = "content">
        <h1>About</h1>
        <p></p>
        </div></section>

        <section id="contact">
            <div class="content">
                <h1>Contact</h1>
                <p><a class="btn btn-default btn-lg" href="#contact-form">Contact Us</a></p>
                <p><iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d5122.204450340393!2d19.91387757798398!3d50.065647167696376!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47165ba756b59b21%3A0xb20c8dba21b317d1!2sAkademia+G%C3%B3rniczo-Hutnicza+im.+Stanis%C5%82awa+Staszica+w+Krakowie!5e0!3m2!1spl!2spl!4v1511628584066" width="500rem" height="500rem" frameborder="0" style="border:0" allowfullscreen></iframe></p>
            </div>
        </section>

        <footer>
           <label class="switch">
       <input type="checkbox"  onchange=" switchTheme(this)">
       <span class="slider"></span>
    </label>
            <p>Copyright©2017 <a href=""></a> for <a href=""> </a></p>
        </footer>

    <!--SIGN UP-->
        <div id="contact-form" class="modal-window">
            <div>
                <a href="#modal-close" title="Close" class="modal-close">Close</a>
                <form action="contact.php">
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
                        <p class="text-danger"><?php echo $errName; ?></p>
                    </div>
                    <div class="form-group">
                        <label for="email">Email address</label>
                        <input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com" value="<?php echo htmlspecialchars($_POST['email']); ?>">
                        <p class="text-danger"><?php echo $errEmail; ?></p>
                    </div>
                    <div class="form-group">
                         <label for="message">Message</label>
                         <textarea class="form-control" rows="4" name="message" value="<?php echo htmlspecialchars($_POST['message']);?>"></textarea>
                         <p class="text-danger"><?php echo $errMessage; ?></p>
                    </div>
                   <div class="form-group">
                         <label for="human">1 + 1 = ?</label>
                         <input type="text" class="form-control" id="human" name="human" pattern=".{1,}" required title="At least 1 character required" placeholder="Your Answer">
                         <p class="text-danger"><?php echo $errHuman; ?></p>
                   </div>
                     <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary btn-lg"></input>
                     <div class="form-group">
                            <?php echo $result; ?>
                     </div>
                </form>
            </div>
        </div>
        <!--END SIGN UP-->

        <!--CONTACT FORM-->
        <div id="contact-form" class="modal-window">
                <a title="Close" class="modal-close">Close</a>
                <form id="contactForm" role="form" method="post" action="contact.php">
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" id="name" name="name" pattern=".{3,}"   required title="At least 3 characters required" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">

                    </div>
                    <div class="form-group">
                        <label for="email">Email address</label>
                        <input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com" pattern=".{3,}"   required title="At least 3 characters required"  value="<?php echo htmlspecialchars($_POST['email']); ?>">
                       <?php echo "<p class='text-danger'>$errEmail</p>";?>
                    </div>
                    <div class="form-group">
                        <label for="message">Message</label>
                        <textarea class="form-control" rows="4" pattern=".{3,}"   required title="At least 3 characters required" name="message">
                            <?php echo htmlspecialchars($_POST['message']);?>
                        </textarea>
                            <?php echo "<p class='text-danger'>$errMessage</p>";?>
                    </div>
                    <div class="form-group">
                        <label for="human">1 + 1 = ?</label>
                        <input type="text" class="form-control" id="human" name="human" pattern=".{1,}"   required title="At least 1 character required" placeholder="Your Answer">
                        <p class='text-danger'>$errHuman</p>
                    </div>
                    <input name="submit" type="submit" value="Send" class="btn btn-primary btn-lg">
                    <div class="form-group">
                        <?php echo $result; ?>
                    </div>
                </form>
        </div>
        <!--CONTACT FORM-->

    </body>
</html>

My contact.php code:

<?php
    if (isset($_POST["submit"])) {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
        $human = intval($_POST['human']);
        $from = 'Generator Contact'; 
        $to = 'kamykx@gmail.com'; 
        $subject = 'Message from AGH Generator Form';

        $body ="From: $name\n E-Mail: $email\n Message:\n $message";

        //CHECK NAME
        if (!$name || empty($name)) {
            $errName = 'Please enter your name';
        }

        //CHECK EMAIL
        if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL) || empty($email)) {
            $errEmail = 'Please enter a valid email address';
        }

        //CHECK MESSAGE
        if (!$message || empty($message)) {
            $errMessage = 'Please enter your message';
        }

        //CHECK IF USER IS NOT A BOT
        if ($human !== 2 || $human !=2) {
            $errHuman = 'Please... proof that you are not a bot :>';
        }

        //SEND THE EMAIL IF THERE ARE NO EXISTING ERRORS
        if (!empty($errName) && !empty($errEmail) && !empty($errMessage) && !empty($errHuman)) {
            if (mail ($to, $subject, $body, $from)) {
                $result='<div class="alert alert-success">Thank You! We will be in touch</div>';
            } else {
                $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
            }
            header("Location: home.php");
        }
    }
?>

EDIT: I've done improvements in my php code (there was logical problem in line error fields are empty: was -> if(!empty($errName)) but should be -> if(empty($errName)). But I've still got and issue. I've compressed the code in order to stay on the same page after contact form submit, but when we click the "submit" button nothing appears (no errors are displayed), page only refreshes and open the form again. What's wrong now? NEW CODE:

<!DOCTYPE HTML>

<html lang="en">

<!--HEAD-->
<head>
    <title>AGH Application for entry with ECTS deficit generator</title>

<!--META-->
    <meta http-equiv="Content-Type" content="text/html"; charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="author" content="SitePoint">
    <meta name="Description" content="It is simple PDF generator for sing with lack of ECTS for another term" />
    <meta name="Keywords" content="ECTS, deficit, deficyt, Poland, Cracow, generator, application, form, pdf, AGH, UST, Akademia, Górniczko, Hutnicza, University, S    cience, Technology, Polska, Kraków, " />

<!--CSS-->
    <link id="theme" rel="stylesheet" href="css/dark.css">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">


<!-- Font Awesome -->
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

</head>
<!--END OF HEAD-->
    <body>
        <script src="https://code.jquery.com/jquery-3.2.1.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
        <script src="js/dropdown.js"></script>
        <script src="js/scrolling-nav.js"></script>
        <script src="js/theme-switch.js"></script>
        <script src="js/nav-position.js"></script>

            <nav id="mainNav">
                <bar>
                    <i id="hamburger" class="fa fa-bars" aria-hidden="true"></i>
                </bar>
                <ul id="menu">
                    <li><a href="#main" class="nav">Main</a></li>
                    <li><a href="#generator" class="nav">Generator</a></li>
                    <li><a href="#about" class="nav">About</a></li>
                    <li><a href="#contact" class="nav">Contact</a></li>
                </ul>
            </nav>

        <section id = "main" >
        <div class = "content">
        <h1>Hello!</h1>
        <p>Welocome to The AGH Application for entry with ECTS deficit generator website. We hope that you use it just for fun :)</p>
        </div></section>

        <section id = "generator">
        <div class = "content">
        <h1>Generator</h1>

        </div></section>

        <section id = "about">
        <div class = "content">
        <h1>About</h1>
        <p>This webapge was created as a project for the Web Technologies. The main reason why it exists is that very common among Students is that they want to apply for entry on another term with ECTS deficit. This site will help students and AGH employees by generating PDF application. We hope that everything at AGH will be fast and growing in the future. We want to make our students life BETTER! </p>
        </div></section>

        <section id="contact">
            <div class="content">
                <h1>Contact</h1>
                <p><a class="btn btn-default btn-lg" href="#contact-form">Contact Us</a></p>
                <?php echo $result; ?>
                <p><iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d5122.204450340393!2d19.91387757798398!3d50.065647167696376!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47165ba756b59b21%3A0xb20c8dba21b317d1!2sAkademia+G%C3%B3rniczo-Hutnicza+im.+Stanis%C5%82awa+Staszica+w+Krakowie!5e0!3m2!1spl!2spl!4v1511628584066" width="500rem" height="500rem" frameborder="0" style="border:0" allowfullscreen></iframe></p>
            </div>
        </section>


        <footer>
           <label class="switch">
       <input type="checkbox"  onchange=" switchTheme(this)">
       <span class="slider"></span>
    </label>
            <p>Copyright©2017 <a href="http://fb.com/marcinkaminskix">Marcin Kamiński</a> for <a href="agh.edu.pl">AGH </a></p>
        </footer>

    <!--SIGN UP-->
        <?php
        if (isset($_POST["send"])) {
            $name = $_POST['name']; //Getting variable from form
            $email = $_POST['email']; //Getting variable from form
            $message = $_POST['message']; //Getting variable from form
            $human = intval($_POST['human']); //Getting variable from form
            $from = 'Generator Contact'; //Set sender
            $to = 'kamykx@gmail.com'; //Where to send an email
            $subject = 'Message from AGH Generator Form'; //Set the subject of email
            $errName = $errEmail = $errMessage = $errHuman = ''; //Values of errors
            $body ="From: $name\n E-Mail: $email\n Message:\n $message"; //Body of email

            //CHECK NAME
            if (empty($name)) {
                $errName = 'Please enter your name';
            }

            //CHECK EMAIL
            if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($email)) {
                $errEmail = 'Please enter a valid email address';
            }

            //CHECK MESSAGE
            if (empty($message)) {
                $errMessage = 'Please enter your message';
            }

            //CHECK IF USER IS NOT A BOT
            if ($human !== 2 || $human !=2) {
                $errHuman = 'Please... proof that you are not a bot :>';
            }

            //SEND THE EMAIL IF THERE ARE NO EXISTING ERRORS
            if (empty($errName) && empty($errEmail) && empty($errMessage) && empty($errHuman)) {
                if (mail($to, $subject, $body, $from)) {
                    $result = '<div class="alert alert-success">Thank You! We will be in touch</div>';
                }
                else {
                    $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
                }
            }
        }
        ?>

        <div id="contact-form" class="modal-window">
            <div>
                <a href="#modal-close" title="Close" class="modal-close">Close</a>
                <form id="contactForm" role="form" method="post">
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
                        <p class="text-danger"><?php echo $errName; ?></p>
                    </div>
                    <div class="form-group">
                        <label for="email">Email address</label>
                        <input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com" value="<?php echo htmlspecialchars($_POST['email']); ?>">
                        <p class="text-danger"><?php echo $errEmail; ?></p>
                    </div>
                    <div class="form-group">
                         <label for="message">Message</label>
                         <textarea class="form-control" rows="4" name="message" value="<?php echo htmlspecialchars($_POST['message']);?>"></textarea>
                         <p class="text-danger"><?php echo $errMessage; ?></p>
                    </div>
                   <div class="form-group">
                         <label for="human">1 + 1 = ?</label>
                         <input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
                         <p class="text-danger"><?php echo $errHuman; ?></p>
                   </div>
                    <button id="send" name="send" type="submit" value="Send" class="btn btn-default btn-lg">Send</button>
                </form>
            </div>
        </div>
        <!--END SIGN UP-->

    </body>
</html>

Your issue is in the logic of this line:

if (!empty($errName) && !empty($errEmail) && !empty($errMessage) && !empty($errHuman)) {

Basically this is saying if everything is wrong, send the email. The not empty check means that there was an error and the variable now holds the error string.

Instead, you just need to create the variables as an empty string and check if they are still empty:

$errName = $errEmail = $errMessage = $errHuman = '';

// CHECK NAME... etc... all the checks

if (empty($errName) && empty($errEmail) && empty($errMessage) && empty($errHuman)) {

However, you're not displaying the error to the user, and you're ending up with a bunch of loose variables. I recommend a slightly different approach using an array of errors...

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    $errors = [];

    //CHECK NAME
    if (!$name || empty($name)) {
        $errors['name'] = 'Please enter your name';
    }

   //CHECK EMAIL
    if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL) || empty($email)) {
        $errors['email'] = 'Please enter a valid email address';
    }

    //etc...

    if (empty($errors)) {
        //send email
    } else {
        $result = '<div class="alert alert-danger">Sorry there was an error sending your message:<br>';
        foreach ($errors as $key => $error) {
            $result .= $error . '<br>';
        }
        $result .= '</div>';
    }

However, if you immediately call a header function after this, the user will never see the error or get a chance to fix it. You can use a query string to send errors back to head.php and display them.

(FYI, the action of a form sends all the POST data to that file, and if there is no action specified, then the form posts to itself.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM