#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2017
    Posts
    232
    Rep Power
    1

    Question Improvements To Member Regsitration Site Reg.php


    Ladies & Gentleman,

    Or should I say 'Gentle Ladies' and 'Hard Men' (tough guys)! :winky:


    Here is my very latest (New Code) reg.php. I have modified it by:

    * Removing outdated strip tags, mysqli_real_escape_string.
    * Bound input parameters on the user reg form.
    * Added htmlspecialcharacters code on output to prevent sql injection.

    Look how cluttered my old code was before a lot of programmers here and other sources helped me out (thanks to all!).

    Ok, my new code does not have the email confirmation code and a lot of others but I will add them soon. I took them out here to make the new code simple for you to easily understand the code. Kept just the fundamentals on the 1st impression. Will add the remaining necessities on the 2nd impression.
    You are welcome to make any suggestions and critisize the coding (but do bother to show an example of an improvement to the area you critisize). Ok ?


    Old Code:

    PHP Code:

    <?php

    //DB connection details.    
    $server_name "localhost";
    $user_name "root";
    $server_password "";
    $db_name "e-id";


    //Connect to DB.
    $conn = new mysqli($server_name,$user_name,$server_password,$db_name);

    if(
    $conn->connect_error)
    {
        die(
    $conn->connect_error);
    }

    //Site details.
    $site_domain "site-domain.com";
    $site_name "site-name";
    $site_admin_email "admin@site-domain.com";

    //Perform following action when user registration "Submit button is clicked".
    if  (isset($_POST['submit']))
    {
        
    //Check if user filled-in "Username", "Password" and "Email" fields or not. If not, give alert to fill them in.
        
    if(!empty($_POST["member_registration_username"]) && !empty($_POST["member_registration_password"])&& !empty($_POST["member_registration_email"]))
        {
            
    $member_registration_username trim(strip_tags(strtolower(mysqli_real_escape_string($conn,$_POST["member_registration_username"]))));
            
    $member_registration_password trim(strip_tags(md5(mysqli_real_escape_string($conn,$_POST["member_registration_password"]))));
            
            
    //Check for Username match in users    table.    
            
    $sql "SELECT * FROM users WHERE Usernames ='".$member_registration_username."'";
            
    $result mysqli_query($conn,$sql);
            
    //If there is a Username match in the "Usernames" column then do the following ...
            
    if(mysqli_num_rows($result)!=0)
            {
                
    //Give alert "username" already taken.
                
    $_SESSION['message']="That Username $member_registration_username is already registered!";
                exit();
            }

            
    //Check for Email match in users table.
            
    $sql "SELECT * FROM users WHERE Emails ='".$member_registration_email."'";
            
    $result mysqli_query($conn,$sql);
            
            
    //If there is a Username match in the "Usernames" column then do the following ...
            
    if(mysqli_num_rows($result)>0)
            {
                
    //Give alert "email" already taken.
                
    $_SESSION['message']="That Email $member_registration_email is already registered!";
                exit();
            }
            
            
    //Dump new "Username", "Email" and "Password" into "users" table.
            
    $sql "INSERT INTO users(Usernames,Passwords,Emails) VALUES('".$member_registration_username."','".$member_registration_password."','".$member_registration_email."')";
            if(
    $sql)
            {
                
    //Give alert dumping new user details into db a success.
                
    $_SESSION['message']="Data insertion into table success!";
            }
            else    
            {
                
    //Give alert dumping new user details into db a failure.
                
    $_SESSION['message']="Data insertion into table failure!";
            }    
        }
        else
        {    
    //Give alert to fill-in all fields.
            
    $_SESSION['message']="You must fill-in all input fields!";
        }
    }

    ?>
    <!DOCTYPE html>
    <html>
    <head>
    <title><?php $site_name ?> Signup Page</title>
      <meta charset="utf-8">
    </head>
    <body>
    <div class = "container">
    <form method="post" action="">
    <center><h2>Signup Form</h2></center>
    <div class="form-group">
    <center><label>Username:</label>
    <input type="text" placeholder="Enter a unique Username" name="member_registration_username" required [A-Za-z0-9]></center>
    </div>
    <div class="form-group">
    <center><label>Password:</label>
    <input type="password" placeholder="Enter a new Password" name="member_registration_password" required [A-Za-z0-9]></center>
    </div>
    <div class="form-group">
    <center><label>Email:</label>
    <input type="email" placeholder="Enter your Email" name="member_registration_email" required [A-Za-z0-9]></center>
    </div>
    <center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
    </form>
    </div>
    </body>
    </html>

    New Code:

    PHP Code:

    <?php

    //Connect to DB.
    require "conn.php";

    //Grab basic site details.
    require "site_details.php";

    //Perform following action when user registration "Submit button is clicked".
    if  (isset($_POST['submit']))
    {
        
    //Check if user filled-in "Username", "Password" and "Email" fields or not. If not, give alert to fill them in.
        
    if(!empty($_POST["member_registration_username"]) && !empty($_POST["member_registration_password"])&& !empty($_POST["member_registration_email"]))
        {
            
    //Check for username match in "Usernames" column in "users"    table. If there is a match then do the following ...
            
    $stmt mysqli_prepare($conn'SELECT COUNT(*) FROM users WHERE usernames = ?');
            
    mysqli_stmt_bind_param($stmt's'$_POST['member_registration_username']);
            
    mysqli_stmt_execute($stmt);
            
    mysqli_stmt_bind_result($stmt$rows);
            if (
    mysqli_stmt_fetch($stmt) && $rows
            {
                die(
                
    'That Username '.htmlspecialchars($_POST['member_registration_username']).' is already registered!'
                
    );
            }

            
    //Check for email match in "Emails" column is "users" table. If there is a match then do the following ...
            
    $stmt mysqli_prepare($conn'SELECT COUNT(*) FROM users WHERE emails = ?');
            
    mysqli_stmt_bind_param($stmt's'$_POST['member_registration_email']);
            
    mysqli_stmt_execute($stmt);
            
    mysqli_stmt_bind_result($stmt$rows);
            if (
    mysqli_stmt_fetch($stmt) && $rows
            {
                die(
                
    'That Email '.htmlspecialchars($_POST['member_registration_email']).' is already registered!'
                
    );
            }
            
            
    //Dump new "Username", "Email" and "Password" into "users" table.        
            
    $name $_POST['member_registration_username'];
            
    $password $_POST['member_registration_email'];
            
    $password $_POST['member_registration_password'];
     
            if (
    $stmt $mysqli->prepare("INSERT INTO tbl_users (name, password) VALUES (?, ?)")) 
            { 
            
    // Bind the variables to the parameter as strings. 
            
    $stmt->bind_param("ss"$name$password);
     
            
    // Execute the statement.
            
    $stmt->execute();
     
            
    // Close the prepared statement.
            
    $stmt->close();
            }    
        }
        else
        {    
    //Give alert to fill-in all fields.
            
    echo "You must fill-in all input fields!";
        }
    }

    ?>
    <!DOCTYPE html>
    <html>
    <head>
    <title><?php $site_name ?> Signup Page</title>
      <meta charset="utf-8">
    </head>
    <body>
    <div class = "container">
    <form method="post" action="">
    <center><h2>Signup Form</h2></center>
    <div class="form-group">
    <center><label>Username:</label>
    <input type="text" name="member_registration_username" required [A-Za-z0-9]></center>
    </div>
    <div class="form-group">
    <center><label>Password:</label>
    <input type="password" name="member_registration_password" required [A-Za-z0-9]></center>
    </div>
    <div class="form-group">
    <center><label>Email:</label>
    <input type="email" name="member_registration_email" required [A-Za-z0-9]></center>
    </div>
    <center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
    </form>
    </div>
    </body>
    </html>

    Fellow programmers, looking at my 2nd code, do you think:

    * it is better;
    * clutter free;
    * more understandable;
    * sql injection free.


    And, on my 2nd code, any chance you can help me convert the INSERT sql command (line 45-55) to mysqli style from pdo ?
    I got that pdo code from:
    3 Ways to Prevent SQL Injection in PHP - wikiHow

    Since most of my code, in my many pages script, is in mysqli or procedural style, it will look odd if 10 lines are pdo or oop style.
    Yes, I know I know, I should do it in pdo and oop style but I'm still a beginner and most tutorials on basic php are in mysqli and procedural style and so I cannot just switch to pdo and oop just yet. Let me learn to walk first and then I'll hop like a Kangaroo. I'm still a toddler. have to take things one step at a time or I'll get confused and put-off from php.

    Question: On my 1st (old code), you will see I don't use the "echo" but "Session Message" instead as 2 youtube tutorials showed to do it that way without giving any explanation why. Therefore, I ask:

    1. What is the difference and benefits (pros) aswell as the cons between the echo and the session message ?
    2. When should I use which one of them ?


    Thanks!
    Last edited by UniqueIdeaMan; April 17th, 2017 at 08:08 AM.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2017
    Posts
    232
    Rep Power
    1
    Ooops! Another source just brought it to my attention that I'm still breaking rules about storing passwords. Suggested me this:

    Never store passwords in a database! - Tom Moertel

    I forgot to hash it. Infact, just gonna read up on hashing now.

    PHP: password_hash - Manual
    PHP: password_verify - Manual
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2017
    Posts
    232
    Rep Power
    1
    Hello Everyone!

    What do you make out of my latest code update ?


    Member Reg & Login script

    config.php

    PHP Code:

    <?php

    /*
    *    ERROR HANDLING
    *    ini_set('display_errors', 1);
    *   ini_set('display_startup_errors', 1);

    *    For All Error, Warning and Notice
    *   error_reporting(E_ALL); OR error_reporting(-1);
    *    For All Errors
    *   error_reporting(E_ERROR);
    *    For All Warnings
    *   error_reporting(E_WARNING);
    *    For All Notice
    *   error_reporting(E_NOTICE);
    */
    error_reporting(E_ALL);

    // session start
    session_start();

    // include files
    include 'conn.php';
    include 
    'site_details.php';

    // include functions
    include 'functions.php';

    ?>

    functions.php

    PHP Code:

    <?php
    // functions file

    /*
    * check if user is logged by checking if session named "user" isset
    * return true if session "user" exists or false if not exists
    */
    function is_logged() {
        if (isset(
    $_SESSION["user"]) && !empty($_SESSION["user"])) {
            return 
    true;
        } else {
            return 
    false;
        }
    }
    ?>

    site_details.php

    PHP Code:

    <?php

    $site_name 
    "Programmer's Haven";
    $site_domain "domain.com";
    $site_admin_email "programmers_haven_admin@domain.com";

    ?>

    reg.php

    PHP Code:

    <?php

    // config.php contains reference to site_details.php (which contains details such as site name, site domain, webmaster email) and conn.php (which contains db connection details).
    include 'config.php';

    // Check if user is already logged in or not.
    if (is_logged() === true) {
        die(
    "You are logged in, can't register.");
    }

    if (
    $_SERVER['REQUEST_METHOD'] == "POST")
    {
        if (isset(
    $_POST["username"]) && 
           isset(
    $_POST["password"]) &&
           isset(
    $_POST["password_confirmation"]) && 
           isset(
    $_POST["email"]) && 
           isset(
    $_POST["email_confirmation"]) && 
           isset(
    $_POST["forename"]) && 
           isset(
    $_POST["gender"]) &&
           isset(
    $_POST["surname"])) {

            
    // Create random hash for email confirmation.
               
    $member_registration_random_numbers sha1(mt_rand(530));

               
    // Account activation link that will verify email.
            
    $account_activation_link "http://www.'".$site_domain."'.com/$site-name/activate_account.php?email='".$_POST['email']."'&hash='".$member_registration_random_numbers."'";

               
    // Remove space in start of string.
               /*
            *    Passwords and email are leaved unescaped here because
            *    if you put them into mysqli_real_escape_string they are not empty.
               */
            
    $username     trim(mysqli_real_escape_string($conn$_POST["username"]));
            
    $password     $_POST["password"];
            
    $password2     $_POST["password_confirmation"];
            
    $forename     trim(mysqli_real_escape_string($conn$_POST["forename"]));
            
    $surname     trim(mysqli_real_escape_string($conn$_POST["surname"]));
            
    $gender     trim(mysqli_real_escape_string($conn$_POST["gender"]));
            
    $email         $_POST["email"];
            
    $email_confirmation $_POST["email_confirmation"];
            
    $email2     trim(mysqli_real_escape_string($conn$email)); // Escaped email for inserting into database
            
    $activation 0// 1 = active | 0 = not active

            // Hashed password.
            
    $hashed_pass password_hash($passwordPASSWORD_DEFAULT); 
        
            
    // Select username and email to check if they exist or not.
            
    $stmt mysqli_prepare($conn"SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
            
    mysqli_stmt_bind_param($stmt'ss'$username$email);
            
    mysqli_stmt_execute($stmt);
            
    $result mysqli_stmt_get_result($stmt);

            
    $row mysqli_fetch_array($resultMYSQLI_ASSOC);

            
    // check if username is registered
            
    if ($row['Usernames'] == $username) {
                
    $_SESSION['error'] = "That username is already registered.";
            
    // check if username is between 6 and 30 characters long
            
    } elseif (strlen($username) < || strlen($username) > 30) {
                
    $_SESSION['error'] = "Username must be between 6 and 30 characters long.";
            
    // check if email is registered
            
    } elseif ($row['Emails'] == $email) {
                
    $_SESSION['error'] = "That email is already registered.";
            
    // check if emails match
            
    } elseif ($email != $email_confirmation) {
                
    $_SESSION['error'] = "Emails don't match.";
            
    // check if email is actual email
            
    } elseif (!filter_var($emailFILTER_VALIDATE_EMAIL)) {
                
    $_SESSION['error'] = "Invalid email format.";
            
    // check if passwords match
            
    } elseif ($password != $password2) {
                
    $_SESSION['error'] = "Passwords don't match.";
            
    // check if password lenght is between 6 and 30 charaters long
            
    } elseif (strlen($password) < || strlen($password) > 30) {
                
    $_SESSION['error'] = "Password must be between 6 and 30 characters long.";
            } else {

                
    // insert query with mysqli prepared statement
                
    $stmt mysqli_prepare($conn"INSERT INTO users(usernames, passwords, emails, forenames, surnames, genders, account_activation_codes, account_activations) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                
    mysqli_stmt_bind_param($stmt'sssssssi'$username$hashed_pass$email2$forename$surname$gender$member_registration_random_numbers$activation);
                
    mysqli_stmt_execute($stmt);

                
    // check if query is inserted
                
    if (mysqli_stmt_insert_id($stmt)) {
                    echo 
    "<h3 style='text-align:center'>Thank you for your registration.<br /> Redirecting to login page ...</h3>";

                    
    // Redirect to login page after 5 seconds
                    
    header("refresh:5;url=login.php");

                    
    // Empty $_SESSION['error'] variable so no more in use, its empty now.
                    
    unset($_SESSION['error']);
                    unset(
    $_POST);
                    exit(); 

                    
    // Email sent to new user with account activation link.
                    
    $to $email;
                    
    $subject "Your '".$site_name."' Account Activation!";
                    
    $body $forename.' '.$surname."\n\n You need to click the following link to confirm your email address and activate your account.\n\n\
                    
    $account_activation_link";
                    
    $from $site_admin_email;
                    
    $headers "from: " $from;
                
                    if (
    mail($to,$subject,$body,$headers)) {
                        
    $_SESSION['error'] = "Registration sucessfuly. Check your email for further instructions!";
                    } else {
                        
    $_SESSION['error'] = "Email not sent, please contact website administrator.";
                    }
                    */
                } else {
                    
    $_SESSION['error'] = "There was a problem with registering, please try again.";
                }

            }
        }
    }


    ?>
    <!DOCTYPE html>
    <html>
        <head>
            <title><?php $site_name ?> Signup Page</title>
        </head>
    <body>
    <div class ="container">

    <?php

    // error messages
    if (isset($_SESSION['error']) && !empty($_SESSION['error'])) {
        echo 
    '<p style="color:red;">'.$_SESSION['error'].'</p>';
    }

    ?>

    <form method="post" action="">
        <center><h2>Signup Form</h2></center>
        <div class="form-group">
            <center><label>Username:</label>
            <input type="text" placeholder="Enter a unique Username" name="username" required [A-Za-z0-9] value="<?php if(isset($_POST['username'])) { echo htmlentities($_POST['username']); }?>"></center>
        </div>
        <div class="form-group">
            <center><label>Password:</label>
            <input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9]></center>
        </div>
        <div class="form-group">
            <center><label>Repeat Password:</label>
            <input type="password" placeholder="Repeat a new Password" name="password_confirmation" required [A-Za-z0-9]></center>
        </div>
        <div class="form-group">
            <center><label>First Name:</label>
            <input type="text" placeholder="Enter your First Name" name="forename" required [A-Za-z] value="<?php if(isset($_POST['forename'])) { echo htmlentities($_POST['forename']); }?>"></center>
        </div>
        <div class="form-group">
            <center><label>Surname:</label>
            <input type="text" placeholder="Enter your Surname" name="surname" required [A-Za-z] value="<?php if(isset($_POST['surname'])) { echo htmlentities($_POST['surname']); }?>"></center>
        </div>
        <div class="form-group">
            <center><label>Gender:</label>
            <input type="radio" name="gender" value="male" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Male<input type="radio" name="gender" value="female" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Female</center>
        </div>
        <div class="form-group">
            <center><label>Email:</label>
            <input type="email" placeholder="Enter your Email" name="email" required [A-Za-z0-9] value="<?php if(isset($_POST['email'])) { echo htmlentities($_POST['email']); }?>"></center>
        </div>
        <div class="form-group">
            <center><label>Repeat Email:</label>
            <input type="email" placeholder="Repeat your Email" name="email_confirmation" required [A-Za-z0-9] value="<?php if(isset($_POST['email_confirmation'])) { echo htmlentities($_POST['email_confirmation']); }?>"></center>
        </div>
        <center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
        <center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>

    </form>

    </div>
    </body>
    </html>

    login.php

    PHP Code:

    <?php
    include 'config.php';

    // check if user is already logged in
    if (is_logged() === true) {
        die(
    "You are already logged in.");
    }

    if (
    $_SERVER['REQUEST_METHOD'] == "POST")
    {
        if (isset(
    $_POST["username_or_email"]) && isset($_POST["password"])) {

            
    $username $_POST["username_or_email"];
            
    $email $_POST["username_or_email"];
            
    $password $_POST["password"];

            
    $stmt mysqli_prepare($conn"SELECT Usernames, Passwords, Emails, Account_Activation_Codes, Account_Activations FROM users WHERE Usernames = ? OR Emails = ?");
            
    mysqli_stmt_bind_param($stmt'ss'$username$email);
            
    mysqli_stmt_execute($stmt);
            
    $result mysqli_stmt_get_result($stmt);

            
    $row mysqli_fetch_array($resultMYSQLI_ASSOC);
            
            
    // check for username and password matching
            
    if ($username == $row['Usernames']  || $email == $row['Emails'] && password_verify($password$row['Passwords'])) {

                
    /* 
                * Check if user has activation link in database, if it has then he has not activated his account
                * or
                * check if user Activation_Accounts is set to 1 its active and 0 is not active.
                */
                
    if ($row['Account_Activation_Codes'] != '' || $row['Account_Activations'] == '0') {
                    
    $error "You didn't activate your account. Please check your email.";
                } else {        

                    
    // if remember me check box is checked set cookie
                    
    if (isset($_POST['remember']) && $_POST['remember'] == "on") {
                        
    /*
                        * if you want to set cookie, set only hash and store it into database
                        * when you come on login page you need to check  if that hash from cookie exists in database
                        * if it exist just start session
                        * NEVER STORE USERNAMES, EMAILS, PASSWORDS AND OTHER USER INFORMATION IN COOKIE
                        */

                        //setcookie("username_or_email", $username_or_email, time()+ (10 * 365 * 24 * 60 * 60));
                        //setcookie("password", $password, time()+ (10 * 365 * 24 * 60 * 60));
                    
    } else {
                        
    // start session
                        
    $_SESSION["user"] = $username;
                        
    $_SESSION["user"] = $email;

                        
    // redirect to member page
                        
    header("Location: home.php");
                        exit();
                    }

                }
                        
            } else {
                
    $error "Invalid username or password.";
            }        
        }
    }    

    ?>
    <!DOCTYPE html>
    <html>
        <head>
            <title><?php $site_name?> Member Login Page</title>
        </head>
    <body>
    <div class="container">
        <form method="post" action="">
        <h3 style="text-align:center;"><?php $site_name ?> Member Login Form</h3>

        <?php if(!empty($error)) { echo '<p style="color:red; text-align:center;">'.$error.'</p>'; } ?>

            <div class="form-group">
                <center><label>Username/Email:</label>
                <input type="text" placeholder="Enter Username or Email" name="username_or_email" required></center>
            </div>
            <div class="form-group">
                <center><label>Password:</label>
                <input type="password" placeholder="Enter password" name="password" required></center>
            </div>
            <div class="form-group">
                <center><label>Remember Login Details:</label>
                <input type="checkbox" name="remember"></center>
            </div>
            <div class="form-group">
                <center><input type="submit" name="submit" value="Login" class="button button-success"></center>
            </div>

            <div class="form-group">
                <center><font color="red" size="3"><b>Forgot your password ?</b><br><a href="member_login_password_reset.php">Reset it here!</a></font></center>
                <center><font color="red" size="3"><b>Not registered ?</b><br><a href="register.php">Register here!</a></font></center>
            </div>
        </form>
    </div>
    </body>
    </html>
    I am getting these absurd errors on reg.php:

    Notice: Undefined variable: site in C:\xampp\htdocs\...\...\register.php on line 24
    Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given in C:\xampp\htdocs\....\...\register.php on line 78
    Warning: mysqli_stmt_execute() expects parameter 1 to be mysqli_stmt, boolean given in C:\xampp\htdocs\...\...\register.php on line 79
    Warning: mysqli_stmt_insert_id() expects parameter 1 to be mysqli_stmt, boolean given in C:\xampp\htdocs\...\...\register.php on line 82


    And these errors on the login.php:

    Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given in C:\xampp\htdocs\...\...\login.php on line 18
    Warning: mysqli_stmt_execute() expects parameter 1 to be mysqli_stmt, boolean given in C:\xampp\htdocs\...\...\login.php on line 19
    Warning: mysqli_stmt_get_result() expects parameter 1 to be mysqli_stmt, boolean given in C:\xampp\htdocs\...\...\login.php on line 20
    Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\...\...\login.php on line 22


    Apart from the error codes. I believe the script is now sql injection free and the password hashing is sound. What is your opinion ?
  6. #4
  7. Banned (not really)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 1999
    Location
    Caro, Michigan
    Posts
    14,780
    Rep Power
    4536
    Well, look at your highlighted code again, and you can see the $site variable highlighted.... I can only assume you meant to refer to a $site-name variable? If so, put it outside of the string like you did with $site_domain or put curly braces around it.
    PHP Code:
    $account_activation_link "http://www.'".$site_domain."'.com/$site-name/activate_account.php?email='".$_POST['email']."'&hash='".$member_registration_random_numbers."'"

    As for the rest, mysqli_prepare() will return FALSE when there is an error. You're not doing any checking for that and always assuming $stmt is a valid statement object that you can use. Your prepare() line is failing, which is causing the warnings on the other lines. "boolean given" is your hint.

    -John
    -- Cigars, whiskey and wild, wild women. --
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2017
    Posts
    232
    Rep Power
    1
    Originally Posted by Sepodati
    Well, look at your highlighted code again, and you can see the $site variable highlighted.... I can only assume you meant to refer to a $site-name variable? If so, put it outside of the string like you did with $site_domain or put curly braces around it.
    PHP Code:
    $account_activation_link "http://www.'".$site_domain."'.com/$site-name/activate_account.php?email='".$_POST['email']."'&hash='".$member_registration_random_numbers."'"

    As for the rest, mysqli_prepare() will return FALSE when there is an error. You're not doing any checking for that and always assuming $stmt is a valid statement object that you can use. Your prepare() line is failing, which is causing the warnings on the other lines. "boolean given" is your hint.

    -John
    Last night, I corrected it to this:

    "$account_activation_link = "http://www.'".$site_domain."'.com/'".$site_name."'/activate_account.php?"
  10. #6
  11. Banned (not really)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 1999
    Location
    Caro, Michigan
    Posts
    14,780
    Rep Power
    4536
    Congrats, you picked the lowest hanging fruit.
    -- Cigars, whiskey and wild, wild women. --
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2017
    Posts
    232
    Rep Power
    1
    Sedopati,


    Can you be kind enough to fix my BIND PARAMS so I don't get these errors ? I'm at a loss how to get this done. I will learn from your sample and other newbies too who visit this thread.
    My errors are mentioned in my original post.
  14. #8
  15. Banned (not really)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 1999
    Location
    Caro, Michigan
    Posts
    14,780
    Rep Power
    4536
    I already told you what was happening with that. Your prepare() statement looks like it's failing. Print out $stmt->error and see what it says.
    -- Cigars, whiskey and wild, wild women. --
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2017
    Posts
    232
    Rep Power
    1
    Errors are gone now!
    I had changed the column names from capital to lower case on the first letters a wk ago and forgotten about it and so did not update the script. Like:
    "Usernames" to "username" and so on. That is why it was not working and spitting errors!
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2017
    Posts
    232
    Rep Power
    1
    Friends,

    You may remember that, I was building a member registration and login script few weeks ago.
    I am now continuing it.
    It has registration.php, login.php and account_activation.php.
    So, when a user registers, the users tbl in the database holds the value "0" in the "account_activation" column and holds the "account activation random numbers (hashed)" as part of the **account activation link**.

    User, then gets emailed a link (account activation link that contains the random numbers) to click to confirm his email and activate his account. When the user clicks this **account activation link**, the "account_activation.php" script gets triggered and takes-over.
    That script, first grabs the user's "email" and "account activation random numbers" details (GET Method) and checks them both against the "users" tbl. If it finds a match then it activates the account and creates a session. Names the session under the username. Then, redirects the user to his account homepage. He no longer needs to type his username and password to login as he is auto logged-in the very moment he clicks the link and activates his account.
    This is very basic and standard stuff.
    I am providing below the account_activation.php. I need you to look at it and tell me if I got the PREPARED STATEMENTS (Binding) correct or not. Throughout the code, I have included comments to make it easy for you to understand what I want the next line of codes to do.
    Note that, I have a former version of this account_activation.php that is working 100%. However, that former version does not prevent sql injection (makes no use of PREPARED STATEMENTS). Hence, I created this new version withe the PREPARED STATEMENTS. I am not sure if I got the BINDING correct or not. I tried checking how the script is functioning by uploading the db to my website to test it on my website but having problems importing it to my website. Originally, I created this script and tested it on xampp. hence, the database and tbl is on xampp. I opened a ticket with my webhost for them to upload the db to my website. In the meanwhile, while I wait for their reply, we might aswell check the script and correct any errors. What do you say ?

    Thanks for your help. Any code suggestions are welcome.

    Code:
    <?php
    session_start();
    include 'config.php';
    
    
    //Grab User's (account activator's) email and account activation code from account activation link's url. Check for email and account activation code details in the account activation link's url.
    if(!isset($_GET["email"], $_GET["account_activation_code"]) === TRUE)
    {
    	$_SESSION['error']="Invalid Email Address! Invalid Account Activation Link! This email is not registered! Try registering an account if you do not already have one! <a href=\"register.php\">Register here!</a>";
    	exit();
    }
    else
    {
    	$confirming_email = trim(mysqli_real_escape_string($conn,$_GET["email"])));
    	$account_activation_code = trim(mysqli_real_escape_string($conn,$_GET["account_activation_code"])));
    		
    	/*
    	Check User's Confirmed Email and Account Activation Code against the "users" tbl to see if it has already been registered or not. 
    	Do this by selecting the Confirmed Email and Account Activation code to check against Mysql DB if they match or not.
    	*/
    	$stmt = mysqli_prepare($conn, "SELECT emails, accounts_activations_codes FROM users WHERE emails = ? AND accounts_activations_codes = ?");
    	mysqli_stmt_bind_param($stmt, 'si', $confirming_email, $account_activation_code);
    	mysqli_stmt_execute($stmt);
    	
    	/* 
    	If the account activation code matches with the confirming Email in the same row in the MySql DB then check if user has already activated his account or not.
    	Check if the associated row is 0" or "1". Must be "0" to indicate account activation is pending.
    	*/
    	if (mysqli_stmt_insert_id($stmt)) 
    	{	
    		while($row = mysqli_fetch_assoc($result)) 
    			{	
    		        $db_username = $row["usernames"];
    				$db_confirmed_email = $row["emails"];
    				$db_account_activation = $row["account_activations"];
    				
    				//If "account_activation" row shows "not equal to 0 (is: 1)", then show error indicating account has already been activated. Then re-direct user to Log-in Page.
    				if($db_account_activation != 0)	
    				{
    					echo "<script>alert('Since your account is already activated, why are you trying to activate it again ? Do not do that again and just login!')</script>";
    					echo "Since your account is already activated, why are you trying to activate it again ? Do not do that again and just login from <a href=\"login.php\">this webpage</a> next time! Make a note of that webpage, ok ?";
    					$conn->close();
    				}
    				else
    				{
    					//Dump the account confirming User's details onto the same row in the "users" table.
    					if (mysqli_stmt_insert_id($stmt)) 
    					{	
    				        // Are lines 42 to 48 (next 5 lines) really necessary ?
    						$stmt = mysqli_prepare($conn, "SELECT usernames, emails, account_actvations FROM users WHERE usernames = ? AND emails = ? AND account_activations_codes = ?");
    						mysqli_stmt_bind_param($stmt, 'ssi', $username, $email, $account_activations_code);
    						mysqli_stmt_execute($stmt);
    						$result = mysqli_stmt_get_result($stmt);
    						
    						// Update 'account_activation' row to '1' to indicate account and email has now been confirmed.
    						$stmt = mysqli_prepare($conn, "UPDATE users SET account_activations = ? WHERE emails = ? AND account_activation_codes = ?";
    						mysqli_stmt_bind_param($stmt, 'isi', 1, $db_confirmed_email, $account_activations_code);
    						//Execute the statement.
    						mysqli_stmt_execute($stmt);
    						
    						//If statement execution a success then create a session under the user's Username.
    						if (mysqli_stmt_insert_id($stmt)) 
    						{
    							echo "<h3 style='text-align:center'>Thank you for your confirming your email and activating your account.<br /> Redirecting you to the login page ...</h3>";
    		
    							$_SESSION["user"] = $db_username;
    					
    							//Redirecting the newly account activated user to his/her account homepage by identifying the user by his/her session name (username).
    							header("location:home.php");
    						}		
    					}
    				}
    			}		
    	}
    	else 
    	{
    		//Give error that this email address (from where the user is clicking the account activation and email confirmation link) is not pending registration. Provide the unregistered user the registration link.
    		echo "<script>alert('Invalid Email Address or Invalid Account Activation Link! This Email $confirming_email was not pending registration with this Account Activation Code $account_activation_code! Try registering an account!')</script>";
    		echo "Invalid Email Address or Invalid Account Activation Link! This Email $confirming_email was not pending registration with this Account Activation Code $account_activation_code! 
    		Try registering an account if you have not already done so! <a href=\"register.php\">Register here!</a>";
        	$conn->close();
    		exit();	
    	}
    }
    
    ?>
  20. #11
  21. Wiser? Not exactly.
    Devshed God 2nd Plane (6000 - 6499 posts)

    Join Date
    May 2001
    Location
    Bonita Springs, FL
    Posts
    6,079
    Rep Power
    4101
    Code:
    if(!isset($_GET["email"], $_GET["account_activation_code"]) === TRUE)
    This is a confusing construct. It's easy to overlook the ! and think this is saying "If these variables are set, return an error" which doesn't make sense. Loose the === TRUE part.

    Code:
    $_SESSION['error']="Invalid Email Address! Invalid Account Activation Link! This email is not registered! Try registering an account if you do not already have one! <a href=\"register.php\">Register here!</a>";
    exit();
    Setting a session variable then exiting doesn't really make sense. Unless you redirect somewhere or have some other script constantly checking that variable the message wouldn't get displayed.

    Code:
    $confirming_email = trim(mysqli_real_escape_string($conn,$_GET["email"])));
    $account_activation_code = trim(mysqli_real_escape_string($conn,$_GET["account_activation_code"])));
    If you're doing parameter binding, don't escape the inputs. By binding the parameter there is no need for escaping and any escapes that get added would be treated as part of the value not an escape.

    Code:
    if (mysqli_stmt_insert_id($stmt))
    You're not inserting anything, so why are you trying to get the ID generated by the last insert operation? Just try to fetch the result of the select query and see if it's successful. If not, then no matching rows were found.

    Code:
    while($row = mysqli_fetch_assoc($result))
    You should probably only be getting a single row back from your query. If so, there's no need for a loop.

    Code:
    $conn->close();
    Let PHP handle closing the connection when it runs it's cleanup stuff at the end of the script, no need to do it manually and potentially cause problems for yourself.

    Code:
    if (mysqli_stmt_insert_id($stmt))
    Again, no insert, so why check for an insert id? I'm not even sure what this check is for since there isn't even a query above it.


    Code:
    // Are lines 42 to 48 (next 5 lines) really necessary ?
    No, you can get whatever fields you need from your initial "Does this user/code combination exist?" query.

    Code:
    mysqli_stmt_bind_param($stmt, 'isi', 1, $db_confirmed_email, $account_activations_code);
    Parameters have to be variables with mysqli, you can't bind a constant. Put that constant 1 into a variable.

    Code:
    if (mysqli_stmt_insert_id($stmt))
    See above

    Code:
    //Redirecting the newly account activated user to his/her account homepage by identifying the user by his/her session name (username).
    header("location:home.php");
    You generally want to exit; after issuing a redirect, or stop further processing in some way. If you don't then PHP will keep processing the script and may do things you didn't want it to do.


    So, you're code should look something like this. It's been a long time since I used MySQLi (PDO is way better, use it) so I may have goofed up something, didn't test it.
    Code:
    <?php
    session_start();
    include 'config.php';
    
    
    if (!isset($_GET["email"], $_GET["account_activation_code"]) === true){
        $_SESSION['error'] = "Invalid Email Address! Invalid Account Activation Link! This email is not registered! Try registering an account if you do not already have one! <a href=\"register.php\">Register here!</a>";
        exit();
    } else {
        $stmt = mysqli_prepare($conn, "SELECT usernames, account_actvations FROM users WHERE emails = ? AND accounts_activations_codes = ?");
        mysqli_stmt_bind_param($stmt, 'si', $_GET["email"],  $_GET["account_activation_code"]);
        mysqli_stmt_bind_result($stmt, $username, $userActivationState);
    
        if (mysqli_stmt_execute($stmt) && mysqli_stmt_fetch($stmt)){
            if ($userActivationState != 0){
                echo "Since your account is already activated, why are you trying to activate it again ? Do not do that again and just login from <a href=\"login.php\">this webpage</a> next time! Make a note of that webpage, ok ?";
                exit;
            }
    
            $userActivationState = 1;
            $stmt = mysqli_prepare($conn, "UPDATE users SET account_activations = ? WHERE usernames = ?");
            mysqli_stmt_bind_param($stmt, 'is', $userActivationState, $username);
            if (mysqli_stmt_execute($stmt)){
                echo "<h3 style='text-align:center'>Thank you for your confirming your email and activating your account.<br /> Redirecting you to the login page ...</h3>";
    
                $_SESSION["user"] = $username;
    
                header("location:home.php");
                exit;
            }
        } else {
            $email = htmlspecialchars($_GET['email']);
            $code = htmlspecialchars($_GET['account_activation_code']);
            echo "Invalid Email Address or Invalid Account Activation Link! This Email $email was not pending registration with this Account Activation Code $code!
            Try registering an account if you have not already done so! <a href=\"register.php\">Register here!</a>";
            exit;
        }
    }
    Your initial "Does this account exist?" query should select the user's primary identifier and whatever other information you'll need. I stuck with your usernames column but if you have an ID value use that instead.

    With mysqli you need to either bind your selected columns to result variables or fetch the result then fetch rows. I added the mysqli_stmt_bind_result call to store the output of the select query. Determine if the user exists by the combination of the query executing successfully and row data being fetched successfully.

    By exiting after your already validated error you can avoid a level of nesting, keeps the code a bit nicer looking.

    When updating the state there's no need to repeat the search condition using the email/code, use the primary identifier instead.

    Escape your inputs before echoing them out into your error message. The script tags aren't really needed, but if you want to use them make sure you properly escape the input for use in scripts also.
    Recycle your old CD's



    If I helped you out, show some love with some reputation, or tip with Bitcoins to 1N645HfYf63UbcvxajLKiSKpYHAq2Zxud
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2017
    Posts
    232
    Rep Power
    1

    Thumbs up


    Originally Posted by kicken
    Code:
    if(!isset($_GET["email"], $_GET["account_activation_code"]) === TRUE)
    This is a confusing construct. It's easy to overlook the ! and think this is saying "If these variables are set, return an error" which doesn't make sense. Loose the === TRUE part.

    Code:
    $_SESSION['error']="Invalid Email Address! Invalid Account Activation Link! This email is not registered! Try registering an account if you do not already have one! <a href=\"register.php\">Register here!</a>";
    exit();
    Setting a session variable then exiting doesn't really make sense. Unless you redirect somewhere or have some other script constantly checking that variable the message wouldn't get displayed.

    Code:
    $confirming_email = trim(mysqli_real_escape_string($conn,$_GET["email"])));
    $account_activation_code = trim(mysqli_real_escape_string($conn,$_GET["account_activation_code"])));
    If you're doing parameter binding, don't escape the inputs. By binding the parameter there is no need for escaping and any escapes that get added would be treated as part of the value not an escape.

    Code:
    if (mysqli_stmt_insert_id($stmt))
    You're not inserting anything, so why are you trying to get the ID generated by the last insert operation? Just try to fetch the result of the select query and see if it's successful. If not, then no matching rows were found.

    Code:
    while($row = mysqli_fetch_assoc($result))
    You should probably only be getting a single row back from your query. If so, there's no need for a loop.

    Code:
    $conn->close();
    Let PHP handle closing the connection when it runs it's cleanup stuff at the end of the script, no need to do it manually and potentially cause problems for yourself.

    Code:
    if (mysqli_stmt_insert_id($stmt))
    Again, no insert, so why check for an insert id? I'm not even sure what this check is for since there isn't even a query above it.


    Code:
    // Are lines 42 to 48 (next 5 lines) really necessary ?
    No, you can get whatever fields you need from your initial "Does this user/code combination exist?" query.

    Code:
    mysqli_stmt_bind_param($stmt, 'isi', 1, $db_confirmed_email, $account_activations_code);
    Parameters have to be variables with mysqli, you can't bind a constant. Put that constant 1 into a variable.

    Code:
    if (mysqli_stmt_insert_id($stmt))
    See above

    Code:
    //Redirecting the newly account activated user to his/her account homepage by identifying the user by his/her session name (username).
    header("location:home.php");
    You generally want to exit; after issuing a redirect, or stop further processing in some way. If you don't then PHP will keep processing the script and may do things you didn't want it to do.


    So, you're code should look something like this. It's been a long time since I used MySQLi (PDO is way better, use it) so I may have goofed up something, didn't test it.
    Code:
    <?php
    session_start();
    include 'config.php';
    
    
    if (!isset($_GET["email"], $_GET["account_activation_code"]) === true){
        $_SESSION['error'] = "Invalid Email Address! Invalid Account Activation Link! This email is not registered! Try registering an account if you do not already have one! <a href=\"register.php\">Register here!</a>";
        exit();
    } else {
        $stmt = mysqli_prepare($conn, "SELECT usernames, account_actvations FROM users WHERE emails = ? AND accounts_activations_codes = ?");
        mysqli_stmt_bind_param($stmt, 'si', $_GET["email"],  $_GET["account_activation_code"]);
        mysqli_stmt_bind_result($stmt, $username, $userActivationState);
    
        if (mysqli_stmt_execute($stmt) && mysqli_stmt_fetch($stmt)){
            if ($userActivationState != 0){
                echo "Since your account is already activated, why are you trying to activate it again ? Do not do that again and just login from <a href=\"login.php\">this webpage</a> next time! Make a note of that webpage, ok ?";
                exit;
            }
    
            $userActivationState = 1;
            $stmt = mysqli_prepare($conn, "UPDATE users SET account_activations = ? WHERE usernames = ?");
            mysqli_stmt_bind_param($stmt, 'is', $userActivationState, $username);
            if (mysqli_stmt_execute($stmt)){
                echo "<h3 style='text-align:center'>Thank you for your confirming your email and activating your account.<br /> Redirecting you to the login page ...</h3>";
    
                $_SESSION["user"] = $username;
    
                header("location:home.php");
                exit;
            }
        } else {
            $email = htmlspecialchars($_GET['email']);
            $code = htmlspecialchars($_GET['account_activation_code']);
            echo "Invalid Email Address or Invalid Account Activation Link! This Email $email was not pending registration with this Account Activation Code $code!
            Try registering an account if you have not already done so! <a href=\"register.php\">Register here!</a>";
            exit;
        }
    }
    Your initial "Does this account exist?" query should select the user's primary identifier and whatever other information you'll need. I stuck with your usernames column but if you have an ID value use that instead.

    With mysqli you need to either bind your selected columns to result variables or fetch the result then fetch rows. I added the mysqli_stmt_bind_result call to store the output of the select query. Determine if the user exists by the combination of the query executing successfully and row data being fetched successfully.

    By exiting after your already validated error you can avoid a level of nesting, keeps the code a bit nicer looking.

    When updating the state there's no need to repeat the search condition using the email/code, use the primary identifier instead.

    Escape your inputs before echoing them out into your error message. The script tags aren't really needed, but if you want to use them make sure you properly escape the input for use in scripts also.
    Thanks Kicken! You're a genius!
    I will check your code out tonight. Might spend half the night trying to learn from it properly in order not to forget what I learn. Got to go out now.
    Had a quick glance and saw a typo. If you test your update and it doesn't work then most likely due to typos and nothing wrong with your coding.
    Here's one typo:

    $stmt = mysqli_prepare($conn, "SELECT usernames, account_actvations FROM users WHERE emails = ? AND accounts_activations_codes = ?");

    Fix that on your end first before running the script (if you ever run the script, that is). Or, you might be wondering what's wrong, if you don't have error reporting on.

    And, if you don't mind. Look out for my other threads.
    Once again, thanks for your precious time editing my code!

    I'm also including below the register.php, login.php, etc.. Just incase you're wondering how far I got to and whether I messed those files up too.
    They are not fully finished yet.
    Just updating you all, how much it's done. Everyone welcome to have a look and comment. Aswell as make cchanges and include in this thread your changes like good old Kicken has!
    Your inputs and contributions to this thread would be available for future newbies too.

    PS - Originally, the PREPARED STATEMENTS were done by another member of another forum as I was stuck. He helped me out there on register.php and maybe login.php (or I copied his code onto login.php. I can't remember), just like Kicken has helped me out on the account_activation.php.
    And so, if you find anything unusual on register.php and/or login.php then that is my mess as I added and/or subtracted a little on these 2 files to tailor the script to my needs.
    So, credit now goes to the other fellow and Kicken for helping me out on the PREPARED STATEMENTS.
    Actually the other person made a lot of changes to my register.php and maybe a little or a lot on the login.php too, His edited the conn.php and added a functions.php. So credit goes to him on those aswell. Sometimes, I just forget how much change it has been made by others and where because I adapt to their style(s) a little and then few days later forget who's lines they were. Mine or their's.
    But, like I said, I had actually finished this member reg-login site script without too much bad coding but that version did not have sql injection prevention. When I tried adding the prevention on the script, you can see how much i messed it up where Kicken had to save the day.
    Anyway, this project is nearly finished thanks to the other programmer from another forum and Kicken. Others are welcome to join in and contribute a little or as much as they can. This project is turning out to be a good learning curve. Thanks to everyone who gave their inputs both in this forum and others!

    config.php

    Code:
    <?php
    
    /*
    ERROR HANDLING
    */
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    
    //For All Error, Warning and Notice
    error_reporting(E_ALL) OR error_reporting(-1);
    //For All Errors
    error_reporting(E_ERROR);
    //For All Warnings
    error_reporting(E_WARNING);
    //For All Notice
    error_reporting(E_NOTICE);
    
    error_reporting(E_ALL);
    
    // session start
    session_start();
    
    // include files
    include 'conn.php';
    include 'site_details.php';
    
    // include functions
    include 'functions.php';
    
    ?>


    conn.php

    Code:
    <?php
    
    $conn = mysqli_connect("localhost", "root", "", "id");
    
    if (!$conn) {
    	// message to use in development to see errors
    	die("Database error : " . mysqli_error($conn));
    
    	// user friendly message
    	// die("Database error.");
    	exit();
    }
    
    ?>


    site_details.php

    Code:
    <?php
    
    $site_name = "id";
    $social_network_name = "id";
    $site_domain = "mymydomain.com";
    $site_admin_email = "id_admin@mymydomain.com";
    $social_network_admin_email = "id_admin@mymydomain.com";
    
    ?>

    functions.php

    Code:
    <?php
    // functions file
    
    /*
    * check if user is logged by checking if session named "user" isset
    * return true if session "user" exists or false if not exists
    */
    function is_logged() {
    	if (isset($_SESSION["user"]) && !empty($_SESSION["user"])) {
    		return true;
    	} else {
    		return false;
    	}
    }
    ?>


    register.php

    Code:
    <?php
    	include 'config.php';
    
    // check if user is already logged in
    if (is_logged() === true) {
    	die("You are logged in. Can't register!");
    }
    
    if ($_SERVER['REQUEST_METHOD'] == "POST")
    {
    	if (isset($_POST["username"]) && 
    	   isset($_POST["password"]) &&
    	   isset($_POST["password_confirmation"]) && 
    	   isset($_POST["email"]) && 
    	   isset($_POST["email_confirmation"]) && 
    	   isset($_POST["first_name"]) && 
    	   isset($_POST["gender"]) &&
    	   isset($_POST["surname"])) {
    
    		// create random hash for email confirmation
    	   	$account_activation_code = sha1(mt_rand(5, 30));
    		// THIS IS NOT GETTING EMAILED !!!
    		$account_activation_link = "http://www.'".$site_domain."'.com/'".$social_network_name."'/activate_account.php?email='".$_POST['email']."'&hash='".$account_activation_code."'";
    
       		// remove space in start of string
       		/*
    		*	passwords and email are leaved unescaped here because
    		*	if you put them into mysqli_real_escape_string they are not empty
       		*/
            $username 	= trim(mysqli_real_escape_string($conn, $_POST["username"]));
    		$password 	= $_POST["password"];
    		$password2 	= $_POST["password_confirmation"];
            $first_name	= trim(mysqli_real_escape_string($conn, $_POST["first_name"]));
            $surname 	= trim(mysqli_real_escape_string($conn, $_POST["surname"]));
    		$gender 	= trim(mysqli_real_escape_string($conn, $_POST["gender"]));
            $email 		= $_POST["email"];
            $email_confirmation = $_POST["email_confirmation"];
            $email2 	= trim(mysqli_real_escape_string($conn, $email)); // Escaped email for inserting into database.
            $account_activation = 0; // 1 = active | 0 = not active
    
            //Hashed Password.
    		$hashed_password = password_hash($password, PASSWORD_DEFAULT);
            
    		//Select Username and Email to check against Mysql DB if they are already registered or not.
    		$stmt = mysqli_prepare($conn, "SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
    		mysqli_stmt_bind_param($stmt, 'ss', $username, $email);
    		mysqli_stmt_execute($stmt);
    		$result = mysqli_stmt_get_result($stmt);
    		
    		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
            
    		// Check if inputted Username is already registered or not.
    		if ($row['usernames'] == $username) {
    			$_SESSION['error'] = "That username is already registered.";
    		// Check if inputted Username is between 8 to 30 characters long or not.
    		} elseif (strlen($username) < 8 || strlen($username) > 30) {
    			$_SESSION['error'] = "Username must be between 8 to 30 characters long!";
    		// Check if inputted Email is already registered or not.
    		} elseif ($row['emails'] == $email) {
    			$_SESSION['error'] = "That email is already registered.";
    		// Check if both inputted EMails match or not.
    		} elseif ($email != $email_confirmation) {
    			$_SESSION['error'] = "Emails don't match!";
    		// Check if inputed Email is valid or not.
    		} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    			$_SESSION['error'] = "Invalid email! Insert your real Email in order for us to email you your account activation details.";
    		// Check if both inputted Passwords match or not.
    		} elseif ($password != $password2) {
    			$_SESSION['error'] = "Passwords don't match.";
    		// Check if Password is between 8 to 30 characters long or not.
    		} elseif (strlen($password) < 8 || strlen($password) > 30) {
    			$_SESSION['error'] = "Password must be between 6 to 30 characters long!";
    		} else {
    
    			//Insert the user's input into Mysql database using php's sql injection prevention method.
    			$stmt = mysqli_prepare($conn, "INSERT INTO users(usernames, passwords, emails, first_names, surnames, genders, accounts_activations_codes, accounts_activations) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    			mysqli_stmt_bind_param($stmt, 'sssssssi', $username, $hashed_password, $email2, $first_name, $surname, $gender, $account_activation_code, $account_activation);
    			mysqli_stmt_execute($stmt);
    
    			//Check if user's registration data was successful submitted or not.
    			if (mysqli_stmt_insert_id($stmt)) {
    				echo "<h3 style='text-align:center'>Thank you for your registration.<br /> Redirecting you to the login page ...</h3>";
    
    				//Send account activation link by email for user to confirm his email and activate his new account.
    				$to = $email;
    				$subject = "Your ".$site_name." account activation !";
    				$body  = nl2br("
    				===============================\r\n
    				".$site_name." \r\n
    				===============================\r\n
    				From: ".$site_admin_email."\r\n
    				To: ".$email."\r\n
    				Subject: Yours ".$subject." account activation \r\n
    				Message: ".$first_name." ".$surname."\r\n You need to click on following <a href=".$site_domain.'activate_account.php?hash='.$account_activation_link.">link</a> to confirm your email address and activate your account. \r\n");
    				$headers = "From: " . $site_admin_email . "\r\n";
    			
    			    if (mail($to,$subject,$body,$headers)) {
    			    	$_SESSION['error'] = "Registration sucessfull. Check your email for further instructions!";
    					
    					//Clear the Session Error so it can no longer be used.
    					unset($_SESSION['error']);
    					unset($_POST);
    					exit();
    					
    					//Redirect user to login page after 5 seconds.
    					header("refresh:5;url=login.php");
    			    } 
    				else 
    				{
    			    	$_SESSION['error'] = "Email not sent, please contact website administrator!";
    			    }			    
    			} 
    			else 
    			{
    				$_SESSION['error'] = "There was a problem in trying to register you! Try again some other time.";
    			}
    	    }
    	}
    }
    
    ?>
    <!DOCTYPE html>
    <html>
    	<head>
    		<title><?php $social_network_name ?> Signup Page</title>
    	</head>
    <body>
    <div class ="container">
    
    <?php
    
    // error messages
    if (isset($_SESSION['error']) && !empty($_SESSION['error'])) {
    	echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
    }
    
    ?>
    
    <form method="post" action="">
    	<center><h2>Signup Form</h2></center>
    	<div class="form-group">
    		<center><label>Username:</label>
    		<input type="text" placeholder="Enter a unique Username" name="username" required [A-Za-z0-9] value="<?php if(isset($_POST['username'])) { echo htmlentities($_POST['username']); }?>"></center>
    	</div>
    	<div class="form-group">
    		<center><label>Password:</label>
    		<input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9]></center>
    	</div>
    	<div class="form-group">
    		<center><label>Repeat Password:</label>
    		<input type="password" placeholder="Repeat a new Password" name="password_confirmation" required [A-Za-z0-9]></center>
    	</div>
    	<div class="form-group">
    		<center><label>First Name:</label>
    		<input type="text" placeholder="Enter your First Name" name="first_name" required [A-Za-z] value="<?php if(isset($_POST['first_name'])) { echo htmlentities($_POST['first_name']); }?>"></center>
    	</div>
    	<div class="form-group">
    		<center><label>Surname:</label>
    		<input type="text" placeholder="Enter your Surname" name="surname" required [A-Za-z] value="<?php if(isset($_POST['surname'])) { echo htmlentities($_POST['surname']); }?>"></center>
    	</div>
    	<div class="form-group">
    		<center><label>Gender:</label>
    		<input type="radio" name="gender" value="male" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Male<input type="radio" name="gender" value="female" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Female</center>
    	</div>
    	<div class="form-group">
    		<center><label>Email:</label>
    		<input type="email" placeholder="Enter your Email" name="email" required [A-Za-z0-9] value="<?php if(isset($_POST['email'])) { echo htmlentities($_POST['email']); }?>"></center>
    	</div>
    	<div class="form-group">
    		<center><label>Repeat Email:</label>
    		<input type="email" placeholder="Repeat your Email" name="email_confirmation" required [A-Za-z0-9] value="<?php if(isset($_POST['email_confirmation'])) { echo htmlentities($_POST['email_confirmation']); }?>"></center>
    	</div>
    	<center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
    	<center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>
    
    </form>
    
    </div>
    </body>
    </html>

    login.php

    Code:
    <?php
    include 'config.php';
    
    // check if user is already logged in
    if (is_logged() === true) {
    	die("You are logged-in! Cannot register as you can only have one account! Note: One account per user.");
    }
    
    if ($_SERVER['REQUEST_METHOD'] == "POST")
    {
    	if (isset($_POST["login_username_or_email"]) && (isset($_POST["login_password"])))
    	{
    		$login_username_or_email = $_POST["login_username_or_email"];
    		$login_username_or_email_2 	= trim(mysqli_real_escape_string($conn, $_POST["login_username_or_email"])); //Escaped Username or Email for checking against Mysql DB.
    		$password = $_POST["login_password"];
    		$hashed_password = password_hash($password, PASSWORD_DEFAULT);
    		
    		/* Select Username And Email to check if either exist in mysql db.
    		Select Password to check if it exists in mysql db.
    		*/
            //Hashed Password.
    		$hashed_password = password_hash($password, PASSWORD_DEFAULT);
            
    		//Select Username and Email to check against Mysql DB if they are already registered or not.
    		$stmt = mysqli_prepare($conn, "SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
    		mysqli_stmt_bind_param($stmt, 'ss', $username, $email);
    		mysqli_stmt_execute($stmt);
    		$result = mysqli_stmt_get_result($stmt);
    		
    		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
    		
    		/* Check for Username or Email match.
    		Check for Password match.
    		*/
    		if ($username == $row['usernames'] || $email == $row['emails'] && password_verify($password, $row['passwords'])) 
    		{		
    		
    		    /* 
            	* check if user have activation link in database, if it have so he is not activated hes account
            	* or
    			* check if user Activation_Accounts is set to 1 its active and 0 is not active
    			*/
            	if ($row['account_activation_codes'] != '' || $row['account_activations'] == '0') 
    			{
            		$error = "You have not activated your account yet! Check your email for further instructions.";
    				exit;
            	} 
    			else 
    			{		
                    //If 'Remember Me' check box is checked then set the cookie.
    	        	if (isset($_POST['remember']) && $_POST['remember'] == "on") 
    				{
    					setcookie("login_username_or_email", $login_username_or_email, time()+ (10 * 365 * 24 * 60 * 60));
    					setcookie("login_password", $login_password, time()+ (10 * 365 * 24 * 60 * 60));                		
    				}
    				else
    				{
    					//If cookie is available then use it to log the user in automatically.
    					if(isset($_COOKIE["login_username_or_email"]))
    					{	
    						setcookie("login_username_or_email", "", "");
    					}
    					if(isset($_COOKIE["login_password"]))
    					{	
    						setcookie("login_password", "", "");
    					}		
    				}
    			header("location:home.php");			
    		    }
    		}
            else
    		{
    	    $message = "Invalid login!";
    		}    
        }
    	else
    	{
    	    $message = "You must input your Account Log-in credentials! (Your Username and Password)";	
        }
    }
    					
    					
    					
    
    		
    				
    		/* OLD CODE BEFORE BINDING:
    		
    		$sql = "SELECT * FROM users WHERE usernames='".$login_username_or_email."' OR emails='".$login_username_or_email."' AND passwords='".$login_password."'";
            $result = mysqli_query($conn,$sql);
    		$numrows = mysqli_num_rows($result);
            if($numrows >1)
    		{		
                while ($row = mysqli_fetch_assoc($result))
    		    {
    			    $db_username = $row["usernames"];
    			    $db_password = $row["passwords"];
    			    $db_email = $row["emails"];
    			                			
                    if  ($login_username_or_email == $db_username && $login_password == $db_password || $login_username_or_email == $db_email && $login_password == $db_password)			
    		        {
    					$_SESSION["user"] = $login_username_or_email;		   
    					if(!empty($_POST["login_remember"]))
    					{
    						setcookie("login_username_or_email", $login_username_or_email, time()+ (10 * 365 * 24 * 60 * 60));
    						setcookie("login_password", $login_password, time()+ (10 * 365 * 24 * 60 * 60));                		
    					}
    					else
    					{
    						if(isset($_COOKIE["login_username_or_email"]))
    						{	
    							setcookie("login_username_or_email", "", "");
    						}
    						if(isset($_COOKIE["login_password"]))
    						{	
    							setcookie("login_password", "", "");
    						}		
    					}
    					header("location:home.php");			
    		        }
    			    else
    		        {
    					$message = "Invalid login!";
    		        }    
    		    }
    	    }
    	    else
    		{
                $message = "Something is wrong! Try again later!";
            }		
    	}
    	else
    	{
    	    $message = "You must input your Username and Password!";	
        }
    }	
    
    */
    
    ?>
    <!DOCTYPE html>
    <html>
    <head>
    <title><?php $site_name?> Member Login Page</title>
      <meta charset="utf-8">
    </head>
    <body>
    <div class = "container">
    <form method="post" action="">
    <center><h3><?php $site_name ?> Member Login Form</h3></center>
    <div class="text-danger">
    <?php
    if(isset($message))
    {
        echo $message;
    }
    ?>
    <div class="form-group">
    <center><label>Username/Email:</label>
    <input type="text" placeholder="Enter Username or Email" name="login_username_or_email" value="<?php if(isset($_COOKIE["login_username_or_email"])) echo $_COOKIE["login_username_or_email"]; ?>"</center>
    </div>
    <div class="form-group">
    <center><label>Password:</label>
    <input type="password" placeholder="Enter password" name="login_password" value="<?php if(isset($_COOKIE["login_password"])) echo $_COOKIE["login_password"]; ?>"></center>
    </div>
    <div class="form-group">
    <center><label>Remember Login Details:</label>
    <input type="checkbox" name="login_remember" /></center>
    </div>
    <div class="form-group">
    <center><input type="submit" name="login_submit" value="Login" class="button button-success" /></center>
    </div>
    <div class="form-group">
    <center><font color="red" size="3"><b>Forgot your password ?</b><br><a href="login_password_reset.php">Reset it here!</a></font></center>
    <center><font color="red" size="3"><b>Not registered ?</b><br><a href="register.php">Register here!</a></font></center>
    </form>
    </div>
    </body>
    </html>


    Logout.php

    Code:
    <?php
           session_start();
           session_destroy();
           echo "You have successfully logged-out!";
    ?><br>
    <?php
           echo "<a href='login.php'>Re-Login.</a>";
    ?><br>
    Last edited by UniqueIdeaMan; July 9th, 2017 at 03:57 PM.
  24. #13
  25. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2017
    Posts
    232
    Rep Power
    1
    Kicken,

    I tried-out your edits on the activate_account.php but I get these errors:

    Notice: A session had already been started - ignoring session_start() in /home/user/public_html/id/config.php on line 21

    Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given in /home/user/public_html/id/activate_account.php on line 22

    Warning: mysqli_stmt_execute() expects parameter 1 to be mysqli_stmt, boolean given in /home/user/public_html/id/activate_account.php on line 23



    I don't understand why I keep getting the session already started error when the session has not been started for me the user who is trying to register a new account using register.php.
    Anyway, to avoid getting the same error again, I load the logout.php and then try registering again after deleting the user's details from my mysql db. But no luck. When everytime I click the account activation link that gets emailed to me, I get those 3 errors and the account_activation.php script gives it.

    To jog your memory, here's how the script is supposed to work ...
    You signup via register.php. After you click the "Register" button, you get an alert:

    Thank you for your registration!
    Check your email for details on how to activate your account you just registered.


    When you check your email, you see a message like this:

    Subject: Your id account activation

    You need to click on following Example Domain link to activate your account by confirming your email address.

    When you click the link, the account_activation script takes over by GETTING the email address and account activation code via GET method. It checks the db if the email address and account activation code exists in the same row or not. If they do, then it checks if the "account_activation" column in the same row shows "1" or "0". If former is found, then it gives warning that account has already been activated. Else, it activates the account by replacing the "0" by "1" (meaning account now active) and redirects the user to his account's homepage (homepage.php) starting a session under his username so he does not need to login.
    Simple script.
    The register.php is working fine. The account_activation.php is showing the 3 errors.
    To be honest, I reckon the errors are really puzzling.
    The 2nd error states:

    Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given in /home/user/public_html/id/activate_account.php on line 22


    And the 3rd error:
    Warning: mysqli_stmt_execute() expects parameter 1 to be mysqli_stmt, boolean given in /home/user/public_html/id/activate_account.php on line 23


    But looking at line 22, do you see any boolean like the error claims and is not the mysqli_stmt_bind_param 1st parameter mentioning the statement that it is so so seeeeking ?

    PHP Code:

    mysqli_stmt_bind_param
    ($stmt'is'$userActivationState$username);
            if (
    mysqli_stmt_execute($stmt)){ 
    Full context:

    PHP Code:

    $stmt 
    mysqli_prepare($conn"UPDATE users SET accounts_activations = ? WHERE usernames = ?");
            
    mysqli_stmt_bind_param($stmt'is'$userActivationState$username);
            if (
    mysqli_stmt_execute($stmt)){
                echo 
    "<h3 style='text-align:center'>Thank you for your confirming your email and activating your account.<br /> Redirecting you to the login page ...</h3>";

                
    $_SESSION["user"] = $username;

                
    header("location:home.php");
                exit;
            } 
    In short, you've given it what it wants in it's 1st parameter. The "Statement". So, why the error ? It is sillyness from php, like these, that waste my time, days, weeks and months and put me off from it. I hope Python won't be like this !!!

    Anyway, here are the files again of the script:


    config.php

    PHP Code:

    <?php

    /*
    ERROR HANDLING
    */
    ini_set('display_errors'1);
    ini_set('display_startup_errors'1);

    //For All Error, Warning and Notice
    error_reporting(E_ALL) OR error_reporting(-1);
    //For All Errors
    error_reporting(E_ERROR);
    //For All Warnings
    error_reporting(E_WARNING);
    //For All Notice
    error_reporting(E_NOTICE);

    error_reporting(E_ALL);

    // session start
    if(!session_start()) {
        
    session_start();
    }

    // include files
    include 'conn.php';
    include 
    'site_details.php';

    // include functions
    include 'functions.php';

    ?>

    functions.php

    PHP Code:

    <?php
    // functions file

    /*
    * check if user is logged by checking if session named "user" isset
    * return true if session "user" exists or false if not exists
    */
    function is_logged() {
        if (isset(
    $_SESSION["user"]) && !empty($_SESSION["user"])) {
            return 
    true;
        } else {
            return 
    false;
        }
    }
    ?>

    conn.php

    PHP Code:

    <?php

    $conn 
    mysqli_connect("localhost""root""""id");

    if (!
    $conn) {
        
    // message to use in development to see errors
        
    die("Database error : " mysqli_error($conn));

        
    // user friendly message
        // die("Database error.");
        
    exit();
    }

    ?>

    site_details.php

    PHP Code:

    <?php

    $site_name 
    "id";
    $social_network_name "id";
    $site_domain "example.com";
    $site_admin_email "id_admin@example.com";
    $social_network_admin_email "id_admin@example.com";

    ?>

    register.php

    PHP Code:

    <?php
        
    include 'config.php';

    // check if user is already logged in
    if (is_logged() === true) {
        die(
    "You are logged in. Can't register!");
    }

    if (
    $_SERVER['REQUEST_METHOD'] == "POST")
    {
        if (isset(
    $_POST["username"]) && 
           isset(
    $_POST["password"]) &&
           isset(
    $_POST["password_confirmation"]) && 
           isset(
    $_POST["email"]) && 
           isset(
    $_POST["email_confirmation"]) && 
           isset(
    $_POST["first_name"]) && 
           isset(
    $_POST["gender"]) &&
           isset(
    $_POST["surname"])) {

            
    // create random hash for email confirmation
               
    $account_activation_code sha1(mt_rand(530));
            
    $account_activation_link "http://www.".$site_domain."/".$social_network_name."/activate_account.php?email=".$_POST['email']."&account_activation_code=".$account_activation_code."";

               
    // remove space in start of string
               /*
            *    passwords and email are leaved unescaped here because
            *    if you put them into mysqli_real_escape_string they are not empty
               */
            
    $username     trim(mysqli_real_escape_string($conn$_POST["username"]));
            
    $password     $_POST["password"];
            
    $password2     $_POST["password_confirmation"];
            
    $first_name    trim(mysqli_real_escape_string($conn$_POST["first_name"]));
            
    $surname     trim(mysqli_real_escape_string($conn$_POST["surname"]));
            
    $gender     trim(mysqli_real_escape_string($conn$_POST["gender"]));
            
    $email         $_POST["email"];
            
    $email_confirmation $_POST["email_confirmation"];
            
    $email2     trim(mysqli_real_escape_string($conn$email)); // Escaped email for inserting into database.
            
    $account_activation 0// 1 = active | 0 = not active

            //Hashed Password.
            
    $hashed_password password_hash($passwordPASSWORD_DEFAULT);
            
            
    //SEE IF BELOW CODE AFTER FOLLOWING WORKS OR NOT AS SUBSTITUTE FUNCTION OVER mysqli_stmt_get_result FUNCTION
            //Select Username and Email to check against Mysql DB if they are already registered or not.
            
    $stmt mysqli_prepare($conn"SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
            
    mysqli_stmt_bind_param($stmt'ss'$username$email);
            
    mysqli_stmt_execute($stmt);
            
    $result mysqli_stmt_get_result($stmt);
            
            
    $row mysqli_fetch_array($resultMYSQLI_ASSOC);
            
            
    // Check if inputted Username is already registered or not.
            
    if ($row['usernames'] == $username) {
                
    $_SESSION['error'] = "That username is already registered.";
            
    // Check if inputted Username is between 8 to 30 characters long or not.
            
    } elseif (strlen($username) < || strlen($username) > 30) {
                
    $_SESSION['error'] = "Username must be between 8 to 30 characters long!";
            
    // Check if inputted Email is already registered or not.
            
    } elseif ($row['emails'] == $email) {
                
    $_SESSION['error'] = "That email is already registered.";
            
    // Check if both inputted EMails match or not.
            
    } elseif ($email != $email_confirmation) {
                
    $_SESSION['error'] = "Emails don't match!";
            
    // Check if inputed Email is valid or not.
            
    } elseif (!filter_var($emailFILTER_VALIDATE_EMAIL)) {
                
    $_SESSION['error'] = "Invalid email! Insert your real Email in order for us to email you your account activation details.";
            
    // Check if both inputted Passwords match or not.
            
    } elseif ($password != $password2) {
                
    $_SESSION['error'] = "Passwords don't match.";
            
    // Check if Password is between 8 to 30 characters long or not.
            
    } elseif (strlen($password) < || strlen($password) > 30) {
                
    $_SESSION['error'] = "Password must be between 6 to 30 characters long!";
            } else {

                
    //Insert the user's input into Mysql database using php's sql injection prevention method.
                
    $stmt mysqli_prepare($conn"INSERT INTO users(usernames, passwords, emails, first_names, surnames, genders, accounts_activations_codes, accounts_activations) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                
    mysqli_stmt_bind_param($stmt'sssssssi'$username$hashed_password$email2$first_name$surname$gender$account_activation_code$account_activation);
                
    mysqli_stmt_execute($stmt);

                
    //Check if user's registration data was successful submitted or not.
                
    if (mysqli_stmt_insert_id($stmt)) {
                    echo 
    "<h3 style='text-align:center'>Thank you for your registration!<br /> Check your email for details on how to activate your account you just registered.</h3>";

                    
    //Send account activation link by email for user to confirm his email and activate his new account.
                    
    $to $email;
                    
    $subject "Your ".$site_name." account activation!";
                    
    $body  nl2br("
                    ===============================\r\n
                    "
    .$site_name." \r\n
                    ===============================\r\n
                    From: "
    .$site_admin_email."\r\n
                    To: "
    .$email."\r\n
                    Subject: Yours "
    .$subject." account activation \r\n
                    Message: "
    .$first_name." ".$surname."\r\n You need to click on following <a href=".$account_activation_link.">link</a> to activate your account by confirming your email address. \r\n");
                    
    $headers "From: " $site_admin_email "\r\n";
                
                    if (
    mail($to,$subject,$body,$headers)) {
                        
    $_SESSION['error'] = "Registration sucessful! Check your email for further instructions!";
                        
                        
    //Clear the Session Error so it can no longer be used.
                        
    unset($_SESSION['error']);
                        unset(
    $_POST);
                        exit();
                        
                        
    //Redirect user to login page after 5 seconds.
                        
    header("refresh:5;url=login.php");
                    } 
                    else 
                    {
                        
    $_SESSION['error'] = "Email not sent, please contact website administrator!";
                    }                
                } 
                else 
                {
                    
    $_SESSION['error'] = "There was a problem in trying to register you! Try again some other time.";
                }
            }
        }
    }

    ?>
    <!DOCTYPE html>
    <html>
        <head>
            <title><?php $social_network_name ?> Signup Page</title>
        </head>
    <body>
    <div class ="container">

    <?php

    // error messages
    if (isset($_SESSION['error']) && !empty($_SESSION['error'])) {
        echo 
    '<p style="color:red;">'.$_SESSION['error'].'</p>';
    }

    ?>

    <form method="post" action="">
        <center><h2>Signup Form</h2></center>
        <div class="form-group">
            <center><label>Username:</label>
            <input type="text" placeholder="Enter a unique Username" name="username" required [A-Za-z0-9] value="<?php if(isset($_POST['username'])) { echo htmlentities($_POST['username']); }?>"></center>
        </div>
        <div class="form-group">
            <center><label>Password:</label>
            <input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9]></center>
        </div>
        <div class="form-group">
            <center><label>Repeat Password:</label>
            <input type="password" placeholder="Repeat a new Password" name="password_confirmation" required [A-Za-z0-9]></center>
        </div>
        <div class="form-group">
            <center><label>First Name:</label>
            <input type="text" placeholder="Enter your First Name" name="first_name" required [A-Za-z] value="<?php if(isset($_POST['first_name'])) { echo htmlentities($_POST['first_name']); }?>"></center>
        </div>
        <div class="form-group">
            <center><label>Surname:</label>
            <input type="text" placeholder="Enter your Surname" name="surname" required [A-Za-z] value="<?php if(isset($_POST['surname'])) { echo htmlentities($_POST['surname']); }?>"></center>
        </div>
        <div class="form-group">
            <center><label>Gender:</label>
            <input type="radio" name="gender" value="male" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Male<input type="radio" name="gender" value="female" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Female</center>
        </div>
        <div class="form-group">
            <center><label>Email:</label>
            <input type="email" placeholder="Enter your Email" name="email" required [A-Za-z0-9] value="<?php if(isset($_POST['email'])) { echo htmlentities($_POST['email']); }?>"></center>
        </div>
        <div class="form-group">
            <center><label>Repeat Email:</label>
            <input type="email" placeholder="Repeat your Email" name="email_confirmation" required [A-Za-z0-9] value="<?php if(isset($_POST['email_confirmation'])) { echo htmlentities($_POST['email_confirmation']); }?>"></center>
        </div>
        <center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
        <center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>

    </form>

    </div>
    </body>
    </html>

    login.php

    PHP Code:

    <?php
    include 'config.php';

    // check if user is already logged in
    if (is_logged() === true) {
        die(
    "You are logged-in! Cannot register as you can only have one account! Note: One account per user.");
    }

    if (
    $_SERVER['REQUEST_METHOD'] == "POST")
    {
        if (isset(
    $_POST["login_username_or_email"]) && (isset($_POST["login_password"])))
        {
            
    $login_username_or_email $_POST["login_username_or_email"];
            
    $login_username_or_email_2     trim(mysqli_real_escape_string($conn$_POST["login_username_or_email"])); //Escaped Username or Email for checking against Mysql DB.
            
    $password $_POST["login_password"];
            
    $hashed_password password_hash($passwordPASSWORD_DEFAULT);
            
            
    /* Select Username And Email to check if either exist in mysql db.
            Select Password to check if it exists in mysql db.
            */
            //Hashed Password.
            
    $hashed_password password_hash($passwordPASSWORD_DEFAULT);
            
            
    //Select Username and Email to check against Mysql DB if they are already registered or not.
            
    $stmt mysqli_prepare($conn"SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
            
    mysqli_stmt_bind_param($stmt'ss'$username$email);
            
    mysqli_stmt_execute($stmt);
            
    $result mysqli_stmt_get_result($stmt);
            
            
    $row mysqli_fetch_array($resultMYSQLI_ASSOC);
            
            
    /* Check for Username or Email match.
            Check for Password match.
            */
            
    if ($username == $row['usernames'] || $email == $row['emails'] && password_verify($password$row['passwords'])) 
            {        
            
                
    /* 
                * check if user have activation link in database, if it have so he is not activated hes account
                * or
                * check if user Activation_Accounts is set to 1 its active and 0 is not active
                */
                
    if ($row['account_activation_codes'] != '' || $row['account_activations'] == '0'
                {
                    
    $error "You have not activated your account yet! Check your email for further instructions.";
                    exit;
                } 
                else 
                {        
                    
    //If 'Remember Me' check box is checked then set the cookie.
                    
    if (isset($_POST['remember']) && $_POST['remember'] == "on"
                    {
                        
    setcookie("login_username_or_email"$login_username_or_emailtime()+ (10 365 24 60 60));
                        
    setcookie("login_password"$login_passwordtime()+ (10 365 24 60 60));                        
                    }
                    else
                    {
                        
    //If cookie is available then use it to log the user in automatically.
                        
    if(isset($_COOKIE["login_username_or_email"]))
                        {    
                            
    setcookie("login_username_or_email""""");
                        }
                        if(isset(
    $_COOKIE["login_password"]))
                        {    
                            
    setcookie("login_password""""");
                        }        
                    }
                
    header("location:home.php");            
                }
            }
            else
            {
            
    $message "Invalid login!";
            }    
        }
        else
        {
            
    $message "You must input your Account Log-in credentials! (Your Username and Password)";    
        }
    }
                        
                        
                        

            
                    
            
    /* OLD CODE BEFORE BINDING:
            
            $sql = "SELECT * FROM users WHERE usernames='".$login_username_or_email."' OR emails='".$login_username_or_email."' AND passwords='".$login_password."'";
            $result = mysqli_query($conn,$sql);
            $numrows = mysqli_num_rows($result);
            if($numrows >1)
            {        
                while ($row = mysqli_fetch_assoc($result))
                {
                    $db_username = $row["usernames"];
                    $db_password = $row["passwords"];
                    $db_email = $row["emails"];
                                            
                    if  ($login_username_or_email == $db_username && $login_password == $db_password || $login_username_or_email == $db_email && $login_password == $db_password)            
                    {
                        $_SESSION["user"] = $login_username_or_email;           
                        if(!empty($_POST["login_remember"]))
                        {
                            setcookie("login_username_or_email", $login_username_or_email, time()+ (10 * 365 * 24 * 60 * 60));
                            setcookie("login_password", $login_password, time()+ (10 * 365 * 24 * 60 * 60));                        
                        }
                        else
                        {
                            if(isset($_COOKIE["login_username_or_email"]))
                            {    
                                setcookie("login_username_or_email", "", "");
                            }
                            if(isset($_COOKIE["login_password"]))
                            {    
                                setcookie("login_password", "", "");
                            }        
                        }
                        header("location:home.php");            
                    }
                    else
                    {
                        $message = "Invalid login!";
                    }    
                }
            }
            else
            {
                $message = "Something is wrong! Try again later!";
            }        
        }
        else
        {
            $message = "You must input your Username and Password!";    
        }
    }    

    */

    ?>
    <!DOCTYPE html>
    <html>
    <head>
    <title><?php $site_name?> Member Login Page</title>
      <meta charset="utf-8">
    </head>
    <body>
    <div class = "container">
    <form method="post" action="">
    <center><h3><?php $site_name ?> Member Login Form</h3></center>
    <div class="text-danger">
    <?php
    if(isset($message))
    {
        echo 
    $message;
    }
    ?>
    <div class="form-group">
    <center><label>Username/Email:</label>
    <input type="text" placeholder="Enter Username or Email" name="login_username_or_email" value="<?php if(isset($_COOKIE["login_username_or_email"])) echo $_COOKIE["login_username_or_email"]; ?>"</center>
    </div>
    <div class="form-group">
    <center><label>Password:</label>
    <input type="password" placeholder="Enter password" name="login_password" value="<?php if(isset($_COOKIE["login_password"])) echo $_COOKIE["login_password"]; ?>"></center>
    </div>
    <div class="form-group">
    <center><label>Remember Login Details:</label>
    <input type="checkbox" name="login_remember" /></center>
    </div>
    <div class="form-group">
    <center><input type="submit" name="login_submit" value="Login" class="button button-success" /></center>
    </div>
    <div class="form-group">
    <center><font color="red" size="3"><b>Forgot your password ?</b><br><a href="login_password_reset.php">Reset it here!</a></font></center>
    <center><font color="red" size="3"><b>Not registered ?</b><br><a href="register.php">Register here!</a></font></center>
    </form>
    </div>
    </body>
    </html>

    logout.php

    PHP Code:

    <?php
           session_start
    ();
           
    session_destroy();
           echo 
    "You have successfully logged-out!";
    ?><br>
    <?php
           
    echo "<a href='login.php'>Re-Login.</a>";
    ?><br>

    activate_account.php

    PHP Code:

    <?php
    session_start
    ();
    include 
    'config.php';


    if (!isset(
    $_GET["email"], $_GET["account_activation_code"]) === true){
        
    $_SESSION['error'] = "Invalid Email Address! Invalid Account Activation Link! This email is not registered! Try registering an account if you do not already have one! <a href=\"register.php\">Register here!</a>";
        exit();
    } else {
        
    $stmt mysqli_prepare($conn"SELECT usernames, accounts_activations FROM users WHERE emails = ? AND accounts_activations_codes = ?");
        
    mysqli_stmt_bind_param($stmt'si'$_GET["email"],  $_GET["account_activation_code"]);
        
    mysqli_stmt_bind_result($stmt$username$userActivationState);

        if (
    mysqli_stmt_execute($stmt) && mysqli_stmt_fetch($stmt)){
            if (
    $userActivationState != 0){
                echo 
    "Since your account is already activated, why are you trying to activate it again ? Do not do that again and just login from <a href=\"login.php\">this webpage</a> next time! Make a note of that webpage, ok ?";
                exit;
            }

            
    $userActivationState 1;
            
    $stmt mysqli_prepare($conn"UPDATE users SET accounts_activations = ? WHERE usernames = ?");
            
    mysqli_stmt_bind_param($stmt'is'$userActivationState$username);
            if (
    mysqli_stmt_execute($stmt)){
                echo 
    "<h3 style='text-align:center'>Thank you for your confirming your email and activating your account.<br /> Redirecting you to the login page ...</h3>";

                
    $_SESSION["user"] = $username;

                
    header("location:home.php");
                exit;
            }
        } else {
            
    $email htmlspecialchars($_GET['email']);
            
    $code htmlspecialchars($_GET['account_activation_code']);
            echo 
    "Invalid Email Address or Invalid Account Activation Link! This Email $email was not pending registration with this Account Activation Code $code!
            Try registering an account if you have not already done so! <a href=\"register.php\">Register here!</a>"
    ;
            exit;
        }
    }

    One other puzzle I have failed to overcome is that, even though the user gets his account activation link looking something like this:

    Example Domain

    The mysql column (account_activation_code) shows only a 4 digit code: b3f0.
    And not the full code which is supposed to be submitted by the register.php: b3f0c7f6bb763af1be91d9e74eabfeb199dc1f1f.
    What is this new puzzle all of a sudden ? I never faced this problem in my register.php before. Mmm.

    Once again, thanks pal, for all your past, present and future helps! I appreciate it and I believe future newbies too who pour into this thread!
    Last edited by UniqueIdeaMan; July 10th, 2017 at 09:10 AM.

IMN logo majestic logo threadwatch logo seochat tools logo