1

So I have the following code:

<body>
          <?php
           $firstname = $lastname = $phone = $phone = $email = $date = $code = "";
           $firstnameerr = $lastnameerr = $phoneerr = $emailerr = $dateerr = $codeerr = "";
           $check = 0;
           $str = "abcdefghijklmnopqrstuvwxyz";
           $rand1 = $str[rand(0, strlen($str) - 1)];
           $rand2 = $str[rand(0, strlen($str) - 1)];
           $rand3 = $str[rand(0, strlen($str) - 1)];
           $rand4 = $str[rand(0, strlen($str) - 1)];
           $rand5 = $str[rand(0, strlen($str) - 1)];
           $final = $rand1 . $rand2 . $rand3 . $rand4 . $rand5;
           if ($_SERVER["REQUEST_METHOD"] == "POST"){  
               if (empty($_POST["ffirstname"])){
                   $firstnameerr = "First Name is empty!";
                   $check = 1;
               } else {
                    $firstname = testInput($_POST['ffirstname']);
                    $check = 0;
                    if (!preg_match("/^[a-zA-Z]*$/",$firstname)){
                        $firstnameerr = "This is not a valid name!";
                        $check = 1;
                    }
               }
               if (empty($_POST["flastname"])){
                   $lastnameerr = "Last Name is empty!";
                   $check = 1;
               } else {
                    $lastname = testInput($_POST['flastname']);
                    $cheek = 0;
                    if (!preg_match("/^[a-zA-Z ]*$/",$lastname)){
                        $lastnameerr = "This is not a valid name";
                        $check = 1;
                    }
               }
               if (empty($_POST["fphone"])){
                   $phoneerr = "Phone field is empty!";
                   $check = 1;
               }else {
                    $phone = testInput($_POST['fphone']);
                    if(!is_numeric($phone)){
                        $phoneerr = "Phone number is not a number";
                        $check = 1;
                    }
               }
               if (empty($_POST["femail"])){
                   $emailerr = "E-mail field is empty!";
               } else {
                   $email = testInput($_POST['femail']);
                   if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                       $emailerr = "E-mail is not valid";
                       $check = 1;
                   }
               }
               if (empty($_POST["fdate"])){
                   $dateerr = "No date selected!";
                   $check = 1;
               } else {
                   $date = testInput($_POST['fdate']);
               }
               if (empty($_POST["fcode"])){
                   $codeerr = "There is no code!";
                   $check = 1;
               } else {
                   $code = $_POST["fcode"];
                   if ($code !== $final){
                       $codeerr = "The code is wrong";
                       $check = 1;
                   }
               }
               if ($check == 0) {     
                    $host = "localhost";
                    $user = "root";
                    $pass = "";
                    $db = "myfirstdb";
                    $connect = new mysqli($host,$user,$pass,$db);
                    if ($connect->connect_error){ 
                        die("Connection failed: " . $connect->connect_error);
                    } else {
                        echo "Connected successfully!";
                    }

                    $sql = "INSERT INTO table1 (firstname , lastname , phone , email , date) VALUES ('$firstname', '$lastname', '$phone', '$email', '$date')";
                    if ($connect->query($sql) === TRUE) {
                        echo "New record created successfully";
                    } else {
                        echo "Error: " . $sql . "<br>" . $connect->error;
                    }

                    $connect->close(); 
                }
            }
            function testInput($data){
                $data = trim($data);
                $data = stripslashes($data);
                $data = htmlspecialchars($data);
                return $data;
            }
    ?>
        <div id="header">
            <img src="http://stupidname.org/files/gfx/design/random%20logos/RandomLogo1.png" alt="logo" height="250px" width="250px">
            <div id="top"><h1 id="first">Welcome to my website</h1></div>
        </div>
        <div id="section">
            <div id="nav">
                <ul>
                    <li><a href="LINK1" id="first">Home</a></li>
                    <li><a href="LINK2">About</a></li>
                    <li><a href="LINK3">Project</a></li>
                    <li><a href="LINK4">Contact</a></li>
                </ul>
            </div>
            <div id="article">
                <h3 style="text-align: center"><b>Please confirm the form below:</b></h3>
                <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                    <p class="namer">First Name</p><br>
                    <input type="text" name="ffirstname" id="ffirstnameid"><span class="error"><?php echo $firstnameerr; ?></span><br>
                    <p class="namer">Last Name</p><br>
                    <input type="text" name="flastname" id="flastnameid"><span class="error"><?php echo $lastnameerr; ?></span><br>
                    <p class="namer">Phone Number</p><br>
                    <input type="text" name="fphone" id="fphoneid"><span class="error"><?php echo $phoneerr; ?></span><br>
                    <p class="namer">E-mail</p><br>
                    <input type="text" name="femail" id="femailid"><span class="error"><?php echo $emailerr; ?></span><br>
                    <p class="namer">Date</p><br>
                    <input type="text" name="fdate" id="fdateid"><span class="error"><?php echo $dateerr; ?></span><br>
                    <p class="namer">Enter the Captcha code!</p><br>
                    <h1><?php echo $final?></h1><br>
                    <input type="text" name="fcode" id="fcodeid"><span class="error"><?php echo $codeerr; ?></span><br>
                    <input type="submit" name="fsubmit" value="Submit">
                </form>
            </div>
        </div>

My problem is with the code a.k.a in the if that uses $code and $final to check wheather it's a human or not. Now whenever i write the exact same thing as in the $final variable the program thinks it's not the same so i get the $codeerr. Can someone please help me fix it?

  • 2
    If you `var_dump($final)` you will se that it is totally different from what you have on your form – u_mulder Oct 24 '16 at 20:36
  • 2
    You generate a random code to display on the form, then you generate another when the form is submitted. Try generating it and putting it in a session var. – AbraCadaver Oct 24 '16 at 20:37
  • Although I appreciate your help, you are wrong. I verified with var_dump and it gave me the exact same string. – Whitewolf3131 Oct 24 '16 at 20:39
  • **Your code is susceptible to SQL INJECTION** Please read this before continuing. Please do not roll your own sanitation. http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Scott Oct 24 '16 at 20:39
  • `$code` will NEVER be equal to `$final` unless some person luckily gets that same exact code when visiting the page as they do upon submitting it; in any case, that visitor should immediately leave your web page and go play the lottery. I really think you should take 2 or 3 doses of PHP Decoction and look at your code again in the morning. – MonkeyZeus Oct 24 '16 at 21:03
  • Yeah just realised that... Just have to find a solution to fix this.... Maybe I should really go get some sleep... – Whitewolf3131 Oct 24 '16 at 21:08
  • Every time you do `$check = 0` you're making it forget any errors in the fields it checked before that. – Barmar Oct 24 '16 at 21:18
  • BTW, for binary variables like `$check` you should use `true` and `false`, not `1` and `0`. – Barmar Oct 24 '16 at 21:19
  • Thank you for pointing this out! However when i rechecked the code a few minutes ago I realised it and deleted the $check = 0. – Whitewolf3131 Oct 24 '16 at 21:28

1 Answers1

0

Ok, I added little changes to your code, and I think it should work now.

<?php
session_start();
?>
<body>
      <?php

       function generateCode() {
           $str = "abcdefghijklmnopqrstuvwxyz";
           $rand1 = $str[rand(0, strlen($str) - 1)];
           $rand2 = $str[rand(0, strlen($str) - 1)];
           $rand3 = $str[rand(0, strlen($str) - 1)];
           $rand4 = $str[rand(0, strlen($str) - 1)];
           $rand5 = $str[rand(0, strlen($str) - 1)];
           return $rand1 . $rand2 . $rand3 . $rand4 . $rand5;
       }

       $firstname = $lastname = $phone = $phone = $email = $date = $code = "";
       $firstnameerr = $lastnameerr = $phoneerr = $emailerr = $dateerr = $codeerr = "";
       $check = 0;

       if(!isset($_SESSION['final'])) {
           $_SESSION['final'] = generateCode();
       }

       if ($_SERVER["REQUEST_METHOD"] == "POST"){  
           if (empty($_POST["ffirstname"])){
               $firstnameerr = "First Name is empty!";
               $check = 1;
           } else {
                $firstname = testInput($_POST['ffirstname']);
                $check = 0;
                if (!preg_match("/^[a-zA-Z]*$/",$firstname)){
                    $firstnameerr = "This is not a valid name!";
                    $check = 1;
                }
           }
           if (empty($_POST["flastname"])){
               $lastnameerr = "Last Name is empty!";
               $check = 1;
           } else {
                $lastname = testInput($_POST['flastname']);
                $cheek = 0;
                if (!preg_match("/^[a-zA-Z ]*$/",$lastname)){
                    $lastnameerr = "This is not a valid name";
                    $check = 1;
                }
           }
           if (empty($_POST["fphone"])){
               $phoneerr = "Phone field is empty!";
               $check = 1;
           }else {
                $phone = testInput($_POST['fphone']);
                if(!is_numeric($phone)){
                    $phoneerr = "Phone number is not a number";
                    $check = 1;
                }
           }
           if (empty($_POST["femail"])){
               $emailerr = "E-mail field is empty!";
           } else {
               $email = testInput($_POST['femail']);
               if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                   $emailerr = "E-mail is not valid";
                   $check = 1;
               }
           }
           if (empty($_POST["fdate"])){
               $dateerr = "No date selected!";
               $check = 1;
           } else {
               $date = testInput($_POST['fdate']);
           }
           if (empty($_POST["fcode"])){
               $codeerr = "There is no code!";
               $check = 1;
           } else {
               $code = $_POST["fcode"];
               if ($code !== $_SESSION['final']){
                   $codeerr = "The code is wrong";
                   $check = 1;
               }
           }
           if ($check == 0) {     
                $host = "localhost";
                $user = "root";
                $pass = "";
                $db = "myfirstdb";
                $connect = new mysqli($host,$user,$pass,$db);
                if ($connect->connect_error){ 
                    die("Connection failed: " . $connect->connect_error);
                } else {
                    echo "Connected successfully!";
                }

                $sql = "INSERT INTO table1 (firstname , lastname , phone , email , date) VALUES ('$firstname', '$lastname', '$phone', '$email', '$date')";
                if ($connect->query($sql) === TRUE) {
                    echo "New record created successfully";
                } else {
                    echo "Error: " . $sql . "<br>" . $connect->error;
                }

                $connect->close(); 
            }
        }

        if($check == 1) {
            $_SESSION['final'] = generateCode();
        }
        function testInput($data){
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
        }
?>
    <div id="header">
        <img src="http://stupidname.org/files/gfx/design/random%20logos/RandomLogo1.png" alt="logo" height="250px" width="250px">
        <div id="top"><h1 id="first">Welcome to my website</h1></div>
    </div>
    <div id="section">
        <div id="nav">
            <ul>
                <li><a href="LINK1" id="first">Home</a></li>
                <li><a href="LINK2">About</a></li>
                <li><a href="LINK3">Project</a></li>
                <li><a href="LINK4">Contact</a></li>
            </ul>
        </div>
        <div id="article">
            <h3 style="text-align: center"><b>Please confirm the form below:</b></h3>
            <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                <p class="namer">First Name</p><br>
                <input type="text" name="ffirstname" id="ffirstnameid"><span class="error"><?php echo $firstnameerr; ?></span><br>
                <p class="namer">Last Name</p><br>
                <input type="text" name="flastname" id="flastnameid"><span class="error"><?php echo $lastnameerr; ?></span><br>
                <p class="namer">Phone Number</p><br>
                <input type="text" name="fphone" id="fphoneid"><span class="error"><?php echo $phoneerr; ?></span><br>
                <p class="namer">E-mail</p><br>
                <input type="text" name="femail" id="femailid"><span class="error"><?php echo $emailerr; ?></span><br>
                <p class="namer">Date</p><br>
                <input type="text" name="fdate" id="fdateid"><span class="error"><?php echo $dateerr; ?></span><br>
                <p class="namer">Enter the Captcha code!</p><br>
                <h1><?php echo $_SESSION['final']?></h1><br>
                <input type="text" name="fcode" id="fcodeid"><span class="error"><?php echo $codeerr; ?></span><br>
                <input type="submit" name="fsubmit" value="Submit">
            </form>
        </div>
    </div>

You must save $final code in $_SESSION for example, because after submit of the form the code for generating $final will get executed and $final will get new value different from the rendered code before submit.

krasipenkov
  • 2,031
  • 1
  • 11
  • 13
  • Nice job, though you forgot something crucial for this to work. You HAVE to start the session through a simple session_start() at the beginning of the php code. However it works like a charm so thank you! :) – Whitewolf3131 Oct 24 '16 at 21:58