0

I am hoping the community can give me a little insight into what is not working with my code, I am following a Udemy course. I have followed the accompanying video which developed an undefined variable error, which after doing some research I believe I have fixed by declaring variables as empty strings being able to be over-ridden by the form data.

The form sends data to the database if both are completed, and if one of the fields is empty then it doesn't, which is as it should be.

If one of the fields is empty it should return a statement asking the user to enter data into the respective field, but nothing is being sent.

The only difference between the tutorial and my code is I have used the materialize framework, where the tutorial used bootstrap, but I can't see that being the issue.

I have attached my code, and commented out redundant parts.

    <?php

    include('php/connection.php');

    //validates data for create user form
    if( isset( $_POST["createUserBtn"])){

        $createUsername = "";
        $createUserPassword = "";
        
        function validateFormData( $formData ) {
            $formData = trim( stripcslashes( htmlspecialchars( $formData)));
            return $formData;
        }

        if( !$_POST["createUsername"]){
            $createUsernameError = "Enter a username <br>";
        } else {
            $createUsername = validateFormData( $_POST["createUsername"]);
        }

        if( !$_POST["createUserPassword"]){
            $createUserPasswordError = "Enter a Password <br>";
        } else {
            $createUserPassword = validateFormData( $_POST["createUserPassword"]);
        }

        if( $createUsername && $createUserPassword) {
            
            $query = "INSERT INTO users (user_id, userName, userPassword) VALUES (NULL, '$createUsername', '$createUserPassword')";

            // if( mysqli_query( $connection, $query)){
            //     echo "New User added";
            // } else {
            //     echo "Error: ".$query."<br>".mysqli_error($connection);
            // }
        }
    }
?>

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

<?php require('static/header.php'); ?>

<?php
    $createUsernameError = "";
    $createUserPasswordError = "";
?>


<div class="col s8 m8 l5 valign-wrapper">
    <div class="container">
        <form action="<?php echo htmlspecialchars( $_SERVER["PHP_SELF"] ); ?>" method="post">
            <div class="row">
                <div class="col s12">
                    <span><h4>Create your user account - create user.php</h4></span>
                    <div class="row form-font">
                        <div class="col s12">
                            <div class="input-field">
                                <a class="red-text"><?php echo $createUsernameError; ?></a>
                                <input placeholder="Enter your username" type="text" name="createUsername">
                                <label for="email">Username</label>
                            </div>
                            <div class="input-field">
                                <a class="red-text"><?php echo $createUserPasswordError; ?></a>
                                <input placeholder="Enter your password" type="password" name="createUserPassword">
                                <label for="password">Password</label>
                            </div>
                            <div class="row left-align">
                                <div class="col s2"></div>
                                <div class="col s8">
                                    <button class="btn-flat waves-effect waves-custom" type="submit" name="createUserBtn"><i class="material-icons left">create</i>Create Account</button>
                                </div>
                                <div class="col s2"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<?php require('static/footer.php'); ?>
</html>
ADyson
  • 57,178
  • 14
  • 51
  • 63
Matthew Webster
  • 137
  • 2
  • 12
  • Can you provide the HTML that is actually received by the browser? And did you check (in your browser's development console) which request is acutally sent when clicking the submit button? – Johannes H. Aug 12 '21 at 19:16
  • When I checked the developer window, nothing is being logged to the console, but the form data is being sent to the database. – Matthew Webster Aug 12 '21 at 20:15
  • `nothing is being logged to the console`...actually, network requests are seen in the Network section of the development tools. Open that section, and then run code your code and see what is logged. (use the Preserve log tick box to ensure logs don't disappear between postbacks / reloads). You can click on a request to see what data was sent in it, and what was received back. – ADyson Aug 12 '21 at 23:58
  • **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Aug 13 '21 at 00:05
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. – ADyson Aug 13 '21 at 00:06
  • Also, please don't store passwords in plain text - that is another security risk. Learn about [password hashing](https://www.php.net/manual/en/faq.passwords.php) instead. – ADyson Aug 13 '21 at 00:06
  • thanks for the feedback, I know there are security issues but that is the next step in the process, but I wanted to understand this issue before moving on to regex & password hashing – Matthew Webster Aug 13 '21 at 12:58
  • Well I've explained the actual issue - see my answer below. Did it help? If so please remember to mark it as accepted. – ADyson Aug 14 '21 at 07:04

1 Answers1

1

Look carefully at your code and the places where you make use of - for example - the $createUsernameError variable.

If there's an error, you set a message in it with this line: $createUsernameError = "Enter a username <br>";. Great, just what you wanted.

However, later on in the code, you run $createUsernameError = "";, which resets it to empty again. And that happens in all circumstances, whether an error was identified or not. And it happens before you try to echo that variable onto the page.

So basically you're setting the value and then immediately blanking it again before you output it. You need to make sure it's only set blank in situations where there's no error. It's the same problem for the password error message.

An easy way to do that would simply be to set the value blank before you run the error checks. Then it'll stay blank if there's no error, but it won't overwrite any error messages which do get set.

So just move these lines:

$createUsernameError = "";
$createUserPasswordError = "";

to the top of your script.


P.S. Please pay attention to the security warnings posted in the comments and urgently fix your code to remove these vulnerabilities before using this code in any kind of live environment. Even if you don't plan to use this code for real, you should still fix these issues so that you learn to do things the correct, safe, reliable way and don't get into bad habits. If you copied this code from a course online, I suggest finding a better course.

ADyson
  • 57,178
  • 14
  • 51
  • 63