2
\$\begingroup\$

I wrote a php script to register a user's bank account and I've tried to make the login as secure as possible, but I wonder if there are any flaws and is it's free from xss attacks and sql injection also the login cookies secession.

Here is the code:

register.php

<?php require('includes/config.php');
j
function test_input($data) {
     $data = trim($data);
     $data = stripslashes($data);
     $data = htmlspecialchars($data);
     $data = filter_var($data, FILTER_SANITIZE_STRING);
     return $data;
}
//if logged in redirect to members page
if( $user->is_logged_in() ){ header('Location: memberpage.php'); }

$getline = test_input($_GET['line']);
$stmt = $db->prepare('SELECT * FROM members WHERE username=:getref');
        $stmt->execute(array(':getref' => $getline));
while($result = $stmt->fetch(PDO::FETCH_ASSOC)){

$referral = $result['username'];
$referralz = $result['referral'];
}

$stmt = $db->prepare('SELECT * FROM members WHERE username = :referrall');
        $stmt->execute(array(':referrall' => $referralz));
while($resultt = $stmt->fetch(PDO::FETCH_ASSOC)){

$sponsor = $resultt['username'];


}

if (empty($referral)){
$referral = "General";

 }

if (empty($sponsor)){
$sponsor = "Omosco";

 }



//if form has been submitted process it
if(isset($_POST['submit'])){

    //very basic validation
        if(strlen($_POST['bankaccount']) < 3){
        $error[] = 'Bank Account is too short.';
}

if(!empty($_POST['bankaccount'])){

$bankaccount = test_input($_POST["bankaccount"]);
        //Checks if name only contains letters and whitespace
        if (!preg_match("/^[0-9]+$/",$bankaccount)) {
            $error[] = 'Bank Account: Only numbers are allowed'; 
        }
}
        if(strlen($_POST['firstname']) < 2){
        $error[] = 'First name is too short.';
}

if(!empty($_POST['firstname'])){

$firstname = test_input($_POST["firstname"]);
        //Checks if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z .]*$/",$firstname)) {
            $error[] = 'Firstname: Only alphabet, dot and white space is allowed'; 
        }
}
        if(strlen($_POST['lastname']) < 2){
        $error[] = 'Last name is too short.';
}

if(!empty($_POST['lastname'])){

$lastname = test_input($_POST["lastname"]);
        //Checks if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z .]*$/",$lastname)) {
            $error[] = 'Lastname: Only alphabet, dot and white space is allowed'; 
        }
}
        if(strlen($_POST['phonenumber']) < 7){
        $error[] = 'Phone number is too short.';
}

if(!empty($_POST['phonenumber'])){

$phonenumber = test_input($_POST["phonenumber"]);
        //Checks if name only contains letters and whitespace
        if (!preg_match("/^((\+)?[1-9]{1,2})?([-\s\.])?((\(\d{1,4}\))|\d{1,4})(([-\s\.])?[0-9]{1,12}){1,2}(\s*(ext|x)\s*\.?:?\s*([0-9]+))?$/",$phonenumber)) {
            $error[] = 'Phone Number: Only number and + is allowed'; 
        }
}
        if(strlen($_POST['country']) < 1){
        $error[] = 'No country selected.';
}

if(!empty($_POST['country'])){

$country = test_input($_POST["country"]);
        //Checks if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z .]*$/",$country)) {
            $error[] = 'Country: Only letters, dot and white space are allowed'; 
        }
}
        if(strlen($_POST['bankname']) < 2){
        $error[] = 'Bank name is too short.';
}

if(!empty($_POST['bankname'])){

$bankname = test_input($_POST["bankname"]);
        //Checks if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z0-9 .]*$/",$bankname)) {
            $error[] = 'BankName: Only number, alphabet, dot and white space are allowed'; 
        }
}

if(!empty($_POST['username'])){

$username = test_input($_POST["username"]);
        //Checks if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z0-9]*$/",$username)) {
            $error[] = 'Username: Only alphabet and number is allowed'; 
        }
}


if(strlen($_POST['username']) < 3){
        $error[] = 'Username is too short.';
    } 



else { 
$usernamexx = test_input($_POST['username']);
        $stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
        $stmt->execute(array(':username' => $usernamexx));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if(!empty($row['username'])){
            $error[] = 'Username provided is already in use.';
        }

    }

if(!empty($_POST['password'])){

$password = test_input($_POST["password"]);
        //Checks if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z0-9]*$/",$password)) {
            $error[] = 'Password: 1 upper/lower case & number is required'; 
        }
}
    if(strlen($_POST['password']) < 3){
        $error[] = 'Password is too short.';
    }

    if(strlen($_POST['passwordConfirm']) < 3){
        $error[] = 'Confirm password is too short.';
    }

    if($_POST['password'] != $_POST['passwordConfirm']){
        $error[] = 'Passwords do not match.';
    }

    //email validation



if(!empty($_POST['email'])){

$email = test_input($_POST["email"]);
        //Checks if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z0-9._*@#]*$/",$email)) {
            $error[] = 'Email: Invalid email address'; 
        }
}

    if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
        $error[] = 'Please enter a valid email address';
    } else {
$emailxx = test_input($_POST['email']);
        $stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
        $stmt->execute(array(':email' => $emailxx));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if(!empty($row['email'])){
            $error[] = 'Email provided is already in use.';
        }

    }


    //if no errors have been created carry on
    if(!isset($error)){

        //hash the password
        $hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);
 $thedate = date("Y-m-d H:i:s");
 $thepause = "pause";
 $thecomment = "Please call me on and after payment. Dont forget to upload the details of your payment.";
        //create the activasion code
        $activasion = md5(uniqid(rand(),true));

        try {

            //insert into database with a prepared statement
            $stmt = $db->prepare('INSERT INTO members (username,password,email,active,sponsor,referral,bankaccount,surname,name,bankname,phone,country,joindate,pause,downlinemsg) VALUES (:username, :password, :email, :active, :sponsor, :referral, :bankaccount, :surname, :name, :bankname, :phone, :country, :joindate, :pause, :downlinemsg)');
            $stmt->execute(array(
                ':username' => $username,
                ':password' => $hashedpassword,
                ':email' => $email,
                ':active' => $activasion,
                ':sponsor' => $sponsor,
                ':referral' => $referral,
                ':bankaccount' => $bankaccount,
                ':surname' => $firstname,
                ':name' => $lastname,
                ':bankname' => $bankname,
                ':phone' => $phonenumber,
                ':country' => $country,
                ':joindate' => $thedate,
                ':pause' => $thepause,
                ':downlinemsg' => $thecomment
            ));
            $id = $db->lastInsertId('memberID');

            //send email
$emailxxx = test_input($_POST['email']);
            $to = $emailxxx;
            $subject = "Registration Confirmation";
            $body = "<p>Thank you for registering at our site.</p>
            <p>To activate your account, please click on this link: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>
            <p>Regards Site Admin</p>";

            $mail = new Mail();
            $mail->setFrom(SITEEMAIL);
            $mail->addAddress($to);
            $mail->subject($subject);
            $mail->body($body);
            $mail->send();

            //redirect to index page
            header('Location: register.php?action=joined');
            exit;

        //else catch the exception and show the error.
        } catch(PDOException $e) {
            $error[] = $e->getMessage();
        }

    }

}

//define page title
$title = 'Register';

//include header template
require('layout/header.php');
?>
<!-- jQuery Form Validation code -->
<script type="text/javascript" language="JavaScript">
<!--
// Password check
$.validator.addMethod("pwcheck", function (value) {    
    return /[a-z]/.test(value) && /[0-9]/.test(value) && /[A-Z]/.test(value)
});

$.validator.addMethod("firstnamev", function (value) {    
    return /^[a-z .]+$/i.test(value)
});
$.validator.addMethod("lastnamev", function (value) {    
    return /^[a-z .]+$/i.test(value)
});

$.validator.addMethod("banknamev", function (value) {    
    return /^[a-z .]+$/i.test(value)
});
$.validator.addMethod("countryv", function (value) {    
    return /^[a-z .]+$/i.test(value)
});
$.validator.addMethod("usernamev", function (value) {    
    return /[a-zA-Z]/.test(value) && /^[a-zA-Z0-9]+$/i.test(value)
});

$.validator.addMethod("phonenumberv", function (value) { return (value.match(/^((\+)?[1-9]{1,2})?([-\s\.])?((\(\d{1,4}\))|\d{1,4})(([-\s\.])?[0-9]{1,12}){1,2}(\s*(ext|x)\s*\.?:?\s*([0-9]+))?$/)); });


$.validator.addMethod('bankaccountv', function (value) {
       return /^[0-9]+$/.test(value);
}),

// Removes Error Message When reCaptcha is Checked Valid
function recaptchaCallback() {
  $('#hiddenRecaptcha').valid();
};

$(function () {

$("#RegisterForm").validate({
        ignore: ".ignore",

        invalidHandler : function() {
            $('html, body').animate({
                scrollTop: $("#RegisterForm").offset().top // scroll top to your form on error
            }, 'slow' );
        },
        // Specify the validation rules
        rules: {
           username: { 
                required: true,
                minlength: 6,
                usernamev: true,
            },
    bankaccount: { 
                required: true,
                minlength: 7,
                bankaccountv: true,
            },
    phonenumber: { 
                required: true,
                minlength: 7,
                phonenumberv: true,
            },
    firstname: { 
                required: true,
                minlength: 2,
                firstnamev: true,
            },
    lastname: { 
                required: true,
                minlength: 2,
                lastnamev: true,
            },
    bankname: { 
                required: true,
                minlength: 2,
                banknamev: true,
            },
    country: { 
                required: true,
                countryv: true,
            },
            email: { 
                required: true,
                email:true,
            },
            password: {
                required: true,
                minlength: 8,
                pwcheck: true,
            },
            passwordConfirm: { 
                required: true,
                equalTo: "#password",
            },
            hiddenRecaptcha: {
                required: function () {
                if (grecaptcha.getResponse() == '') {
                     return true;
                } else {
                     return false;
                }
              }             
           },
       },

        // Specify the validation error messages
        messages: {
            username: {
                required: "Please enter username",
                usernamev: "Invalid username"
            },
            bankaccount: {
                required: "Please enter Bank Account",
                bankaccountv: "Enter valid bank account"
            },
            bankname: {
                required: "Please enter Bank Name",
                banknamev: "Enter valid bank name"
            },
            firstname: {
                required: "Please enter first name",
                firstnamev: "Enter valid Surname"
            },
            lastname: {
                required: "Please enter last name",
                lastnamev: "Enter valid name"
            },
            country: {
                required: "Please select country",
                countryv: "Enter valid Country"
            },
            phonenumber: {
                required: "Please enter Phone Number",
                phonenumberv: "Enter valid phone number"
            },
            email: {
                required: "Please enter an Email",
            },
            password: {
                required: "Password required",
                minlength: "Minumum length 8",
                pwcheck: "1 upper/lower case &amp; number required"
            },
            passwordConfirm: {
                required: "Please confirm password",
                equalTo: "Passwords do not match"
            },
            hiddenRecaptcha: {
                required: "Human response required"
            },
            submitHandler: function(form) // CALLED ON SUCCESSFUL VALIDATION
            // Redirect can be removed from here
                {
                window.location.replace=''; // Add your custom form submitted redirect page
            }
            // Redirect can be removed to here
        },
   });

});
-->
</script>
<style type="text/css">
<!--
.outer-margin {
 margin:2px;
 }
.wrapper{
  max-width:320px;
  margin: 0 auto; /* position left. right and atuo for middle  */
  margin-top:18px;
  border:solid 1px #DDDDDD;
  border-radius:0px 0px 5px 5px;
  }
.header {
  font-size:20px;
  font-weight:normal;
  color:white;
  background-color:navy;
  padding:5px;
  margin-bottom:10px;
  }
.main {
  padding:10px;
  }
::-webkit-input-placeholder {
    color:#888;
}
:-moz-placeholder {
    color:#888;
}
::-moz-placeholder {
    color:#888;
}
:-ms-input-placeholder {
    color:#888;
}
/* Placeholder disappears on focus */
input:focus::-webkit-input-placeholder  {color:transparent !IMPORTANT;}
input:focus::-moz-placeholder   {color:transparent !IMPORTANT;}
input:-moz-placeholder   {color:transparent !IMPORTANT;}
textarea:focus::-webkit-input-placeholder  {color:transparent !IMPORTANT;}
textarea:focus::-moz-placeholder   {color:transparent !IMPORTANT;}
textarea:-moz-placeholder   {color:transparent !IMPORTANT;}
.input-row {
  display:block;
  min-height:85px;
  margin-bottom:-5px;
}
-->
</style>
<div class="outer-margin">
  <div class="wrapper">
    <!-- Header -->
    <div class="header">&nbsp;Registration</div>
    <div  class="main">
      <form name="RegisterForm" id="RegisterForm" role="form" action="" method="post" autocomplete="off">
        <?php
       //check for any errors
       if(isset($error)){
           foreach($error as $error){
             echo '<p class="bg-danger">'.$error.'</p>';
           }
       }

       //if action is joined show sucess
$getacttt = test_input($_GET['action']);
       if(isset($getacttt) && $getacttt == 'joined'){
           echo "<div class='bg-success'>Registration successful, please check your email to activate your account.</div>";
       }
      ?>
        <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="username">Username</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input name="username" id="username" type="text" placeholder="Enter Username" class="form-control" maxlength="50" value="<?php if(isset($error)){ echo $username; } ?>" tabindex="1">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="username" generated="true"></label>
          </div>
        </div>
        <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="email">Email</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
              <input type="email" name="email" id="email" placeholder="Enter Email" class="form-control" maxlength="100" value="<?php if(isset($error)){ echo $email; } ?>" tabindex="2">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="email" generated="true"></label>
          </div>
        </div>


<center><b>Below information can be change any time.</b></center>
 <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="bankaccount">Bank Account</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input name="bankaccount" id="bankaccount" type="text" placeholder="Enter Bank Account" class="form-control" maxlength="50" value="<?php if(isset($error)){ echo $bankaccount; } ?>" tabindex="1">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="bankaccount" generated="true"></label>
          </div>
        </div>
 <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="firstname">First Name</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input name="firstname" id="firstname" type="text" placeholder="Correspond With Your Bank Acct" class="form-control" maxlength="50" value="<?php if(isset($error)){ echo $firstname; } ?>" tabindex="1">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="firstname" generated="true"></label>
          </div>
        </div>
 <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="lastname">Last Name</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input name="lastname" id="lastname" type="text" placeholder="Correspond With Your Bank Acct" class="form-control" maxlength="50" value="<?php if(isset($error)){ echo $lastname; } ?>" tabindex="1">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="lastname" generated="true"></label>
          </div>
        </div>
 <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="bankname">Bank Name</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input name="bankname" id="bankname" type="text" placeholder="Enter Bank Name" class="form-control" maxlength="50" value="<?php if(isset($error)){ echo $bankname; } ?>" tabindex="1">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="bankname" generated="true"></label>
          </div>
        </div>
 <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="phonenumber">Phone Number (+)</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input name="phonenumber" id="phonenumber" type="text" placeholder="Enter Phone Number e.g +13..." class="form-control" maxlength="50" value="<?php if(isset($error)){ echo $phonenumber; } ?>" tabindex="1">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="phonenumber" generated="true"></label>
          </div>
        </div>




        <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="password">Password</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
              <input name="password" id="password" placeholder="Enter Password" class="form-control" maxlength="20" type="password" tabindex="3">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="password" generated="true"></label>
          </div>
        </div>
        <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="passwordConfirm">Confirm Password</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
              <input type="password" name="passwordConfirm" id="passwordConfirm" placeholder="Re-Enter Password" maxlength="20" class="form-control"  tabindex="4">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="passwordConfirm" generated="true"></label>
          </div>
        </div>

<div class="input-row">


<select name="country" id="country">
  <option value="">Select Country</option>
  <option value="Nigeria">Nigeria</option>
</select>
</div>

        <!-- NoCaptcha -->
        <div style="display:block; min-height:130px; margin-top:-5px;">
          <label class="control-label" for="hiddenRecaptcha">Security</label>
          <!-- Google No Captcha Human Security Scripts -->
          <input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
          <div class="g-recaptcha" data-sitekey="6Ldujg4UAAAAAN2uBXYSYvGpd2LqPglPlgZ2Fqcx" style="transform:scale(0.90);-webkit-transform:scale(0.90);transform-origin:0 0;-webkit-transform-origin:0 0; color:transparent; font-weight:normal; line-height:0px;" tabindex="5"> </div>
          <div>
            <label style="color:red; font-weight:normal; position:relative; top:-10px;" class="error" for="hiddenRecaptcha" generated="true"></label>
          </div>
        </div>
        <!-- Button -->
        <div class="input-row" style="margin-top:-5px; margin-bottom:-30px;">
          <!-- For sliver button change btn-primary to btn-default - you can add button width:100%; for full width button -->
          <input type="submit" name="submit" value="Register" class="btn btn-primary" tabindex="4">
          <span style="position:relative; bottom:-8px; left:5px;">Already a member? <a href="login.php">Login</a></span> </div>
      </form>
    </div>
  </div>
</div>

<?php
//include header template
require('layout/footer.php');
?>

login.php

<?php
//include config
require_once('includes/config.php');

function test_input($data) {
     $data = trim($data);
     $data = stripslashes($data);
     $data = htmlspecialchars($data);
     $data = filter_var($data, FILTER_SANITIZE_STRING);
     return $data;
}
//check if already logged in move to home page
if( $user->is_logged_in() ){ header('Location: index.php'); } 

//process login form if submitted
if(isset($_POST['submit'])){

    $username = test_input($_POST['username']);
    $password = test_input($_POST['password']);

    if($user->login($username,$password)){ 
        $_SESSION['username'] = $username;
        header('Location: memberpage.php');
        exit;

    } else {
        $error[] = 'Wrong username or password or your account has not been activated.';
    }

}//end if submit

//define page title
$title = 'Login';

//include header template
require('layout/header.php'); 
?>
<!-- jQuery Form Validation code -->
<script type="text/javascript" language="JavaScript">
<!--
// Removes Error Message When reCaptcha is Checked Valid
function recaptchaCallback() {
  $('#hiddenRecaptcha').valid();
};

$(function () {

$("#UsernameLoginForm").validate({
        ignore: ".ignore",

        invalidHandler : function() {
            $('html, body').animate({
                scrollTop: $("#UsernameLoginForm").offset().top // scroll top to your form on error
            }, 'slow' );
        },
        // Specify the validation rules
        rules: {
           username: {
                required: true,
                minlength: 6,
            },
            password: {
                required: true,
            },
            hiddenRecaptcha: {
                required: function () {
                if (grecaptcha.getResponse() == '') {
                     return true;
                } else {
                     return false;
                }
              }             
           },
       },

        // Specify the validation error messages
        messages: {
            username: {
                required: "Please enter your username",
            },
            password: {
                required: "Please enter your password",
            },
            hiddenRecaptcha: {
                required: "Human response required"
            },
            submitHandler: function(form) // CALLED ON SUCCESSFUL VALIDATION
            // Redirect can be removed from here
                {
                window.location.replace='redirect-when-logged-in.php'; // Add your custom form submitted redirect
            }
            // Redirect can be removed to here
        },
   });

});
-->
</script>
<style type="text/css">
<!--
.outer-margin {
 margin:2px;
 }
.wrapper{
  max-width:320px;
  margin: 0 auto; /* position left. right and atuo for middle  */
  margin-top:18px;
  border:solid 1px #DDDDDD;
  border-radius:0px 0px 5px 5px;
  }
.header {
  font-size:20px;
  font-weight:normal;
  color:white;
  background-color:navy;
  padding:5px;
  margin-bottom:10px;
  }
.main {
  padding:10px;
  }
::-webkit-input-placeholder {
    color:#888;
}
:-moz-placeholder {
    color:#888;
}
::-moz-placeholder {
    color:#888;
}
:-ms-input-placeholder {
    color:#888;
}
/* Placeholder disappears on focus */
input:focus::-webkit-input-placeholder  {color:transparent !IMPORTANT;}
input:focus::-moz-placeholder   {color:transparent !IMPORTANT;}
input:-moz-placeholder   {color:transparent !IMPORTANT;}
textarea:focus::-webkit-input-placeholder  {color:transparent !IMPORTANT;}
textarea:focus::-moz-placeholder   {color:transparent !IMPORTANT;}
textarea:-moz-placeholder   {color:transparent !IMPORTANT;}
.input-row {
  display:block;
  min-height:85px;
  margin-bottom:-5px;
}
-->
</style>
<!-- End Head -->
</head><body>
<!-- Place All in Body -->
<div class="outer-margin">
  <div class="wrapper">
    <!-- Header -->
    <div class="header">&nbsp;Login</div>
    <div class="main">
      <!-- YOUR WILL NEED TO SET YOUR FORM action="" OR REMOVE IF REQUIRED BY YOUR PHP SCRIPT -->
      <form name="UsernameLoginForm" id="UsernameLoginForm" role="form" action="" method="post" autocomplete="off">
               <?php
                //check for any errors
                if(isset($error)){
                    foreach($error as $error){
                        echo '<p class="bg-danger">'.$error.'</p>';
                    }
                }
    $useraction = test_input($_GET['action']);

                if(isset($useraction)){

                    //check the action
                    switch ($useraction) {
                        case 'active':
                            echo "<div class='bg-success'>Your account is now active you may now log in.</div>";
                            break;
                        case 'reset':
                            echo "<div class='bg-success'>Please check your inbox for a reset link.</div>";
                            break;
                        case 'resetAccount':
                            echo "<div class='bg-success'>Password changed, you may now login.</div>";
                            break;
                    }

                }


                ?>
        <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="username">Username</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input  name="username" id="username" placeholder="Username" class="form-control" type="text" value="<?php if(isset($error)){ echo $username; } ?>" maxlength="50" tabindex="1">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="username" generated="true"></label>
          </div>
        </div>
        <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="password">Password</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
              <input name="password" id="password" placeholder="Password" class="form-control" type="password" maxlength="20" tabindex="2">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="password" generated="true"></label>
          </div>
        </div>
        <!-- NoCaptcha -->
        <div style="display:block; min-height:130px; margin-top:-5px;">
          <label class="control-label" for="hiddenRecaptcha">Security</label>
          <!-- Google No Captcha Human Security Scripts -->
          <input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
          <div class="g-recaptcha" data-sitekey="6Ldujg4UAAAAAN2uBXYSYvGpd2LqPglPlgZ2Fqcx" style="transform:scale(0.90);-webkit-transform:scale(0.90);transform-origin:0 0;-webkit-transform-origin:0 0; color:transparent; font-weight:normal; line-height:0px;" tabindex="3"> </div>
          <div>
            <label style="color:red; font-weight:normal; position:relative; top:-10px;" class="error" for="hiddenRecaptcha" generated="true"></label>
          </div>
        </div>
        <!-- Button -->
        <div class="input-row" style="margin-top:-5px; margin-bottom:-30px;">
          <!-- For sliver button change btn-primary to btn-default - you can add button width:100%; for full width button -->
          <input type="submit" name="submit" value="Login" class="btn btn-primary" tabindex="4">
          <span style="position:relative; bottom:-8px; left:5px;"><a href="register.php">Join</a> | <a href="reset.php">Forgot your password?</a></span> </div>
      </form>
    </div>
  </div>
</div>

<?php 
//include header template
require('layout/footer.php'); 
?>

editact.php

<?php require('includes/config.php'); 

function test_input($data) {
     $data = trim($data);
     $data = stripslashes($data);
     $data = htmlspecialchars($data);
     $data = filter_var($data, FILTER_SANITIZE_STRING);
     return $data;
}
 $membereditz = "memberedit";
 $memberlogz = "memberlog";
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); } 
else
{
$stmt = $db->prepare('SELECT * FROM members WHERE username=:username');
        $stmt->execute(array(':username' => $_SESSION['username']));
while($result = $stmt->fetch(PDO::FETCH_ASSOC)){



$email = test_input($result['email']);
$firstname = test_input($result['surname']);
$lastname = test_input($result['name']);
$phonenumber = test_input($result['phone']);
$bankname = test_input($result['bankname']);
$bankaccount = test_input($result['bankaccount']);
$whatsapp = test_input($result['whatsapp']);
$admban = test_input($result['ban']);
$message = test_input($result['downlinemsg']);
 }


if($admban=='0'){

//if form has been submitted process it
if(isset($_POST['submit'])){

    //very basic validation
        if(strlen($_POST['bankaccount']) < 3){
        $error[] = 'Bank Account is too short.';
}

if(!empty($_POST['bankaccount'])){

$bankaccount1 = test_input($_POST["bankaccount"]);
        //Checks if name only contains letters and whitespace
        if (!preg_match("/^[0-9]+$/",$bankaccount)) {
            $error[] = 'Bank Account: Only numbers are allowed'; 
        }
}
        if(strlen($_POST['firstname']) < 2){
        $error[] = 'First name is too short.';
}

if(!empty($_POST['firstname'])){

$firstname1 = test_input($_POST["firstname"]);
        //Checks if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z .]*$/",$firstname)) {
            $error[] = 'Firstname: Only alphabet, dot and white space is allowed'; 
        }
}
        if(strlen($_POST['lastname']) < 2){
        $error[] = 'Last name is too short.';
}
if(!empty($_POST['lastname'])){

$lastname1 = test_input($_POST["lastname"]);
        //Checks if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z .]*$/",$lastname)) {
            $error[] = 'Lastname: Only alphabet, dot and white space is allowed'; 
        }
}
        if(strlen($_POST['phonenumber']) < 7){
        $error[] = 'Phone number is too short.';
}
if(!empty($_POST['phonenumber'])){

$phonenumber1 = test_input($_POST["phonenumber"]);
        //Checks if name only contains letters and whitespace
        if (!preg_match("/^((\+)?[1-9]{1,2})?([-\s\.])?((\(\d{1,4}\))|\d{1,4})(([-\s\.])?[0-9]{1,12}){1,2}(\s*(ext|x)\s*\.?:?\s*([0-9]+))?$/",$phonenumber)) {
            $error[] = 'Phone Number: Only number and + is allowed'; 
        }
}
if(!empty($_POST['whatsapp'])){

$whatsapp1 = test_input($_POST["whatsapp"]);
 if (!preg_match("/^((\+)?[1-9]{1,2})?([-\s\.])?((\(\d{1,4}\))|\d{1,4})(([-\s\.])?[0-9]{1,12}){1,2}(\s*(ext|x)\s*\.?:?\s*([0-9]+))?$/",$whatsapp1)) {
            $error[] = 'Phone Number: Only number and + is allowed'; 
        }}

        if(strlen($_POST['bankname']) < 2){
        $error[] = 'Bank name is too short.';
}

    if(!empty($_POST['bankname'])){

$bankname1 = test_input($_POST["bankname"]);
        //Checks if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z0-9 .]*$/",$bankname)) {
            $error[] = 'BankName: Only number, alphabet, dot and white space are allowed'; 
        }
}


    //if no errors have been created carry on
    if(!isset($error)){



        try {

            //insert into database with a prepared statement
                $idd = $_SESSION['memberID'];


$dmessage = test_input($_POST["message"]);

    $sql = "UPDATE members SET  bankaccount=:bankaccount, surname=:surname, name=:name, bankname=:bankname, downlinemsg=:downlinemsg, phone=:phone, whatsapp=:whatsapp WHERE memberID=:idd";

   $stmt = $db->prepare($sql);

$stmt->bindValue(":bankaccount", $bankaccount1, PDO::PARAM_STR);
    $stmt->bindValue(":surname", $firstname1, PDO::PARAM_STR);
    $stmt->bindValue(":name", $lastname1, PDO::PARAM_STR);
    $stmt->bindValue(":bankname", $bankname1, PDO::PARAM_STR);
    $stmt->bindValue(":phone", $phonenumber1, PDO::PARAM_STR);
    $stmt->bindValue(":downlinemsg", $dmessage, PDO::PARAM_STR);
    $stmt->bindValue(":whatsapp", $whatsapp1, PDO::PARAM_STR);
    $stmt->bindValue(":idd", $idd, PDO::PARAM_STR);
    $stmt->execute();


            $id = $db->lastInsertId('memberID');

            //send email
            $to = $email;
            $subject = "Your Details Has Changed";
            $body = "<p>Your account details successfully changed.</p>

            <p>Regards Site Admin</p>";

            $mail = new Mail();
            $mail->setFrom(SITEEMAIL);
            $mail->addAddress($to);
            $mail->subject($subject);
            $mail->body($body);
            $mail->send();

            //redirect to index page
            header('Location: editacct.php?action=changed');
            exit;

        //else catch the exception and show the error.
        } catch(PDOException $e) {
            $error[] = $e->getMessage();
        }

    }

}

//define page title
$title = 'Edit Account';

//include header template
require('layout/header.php');
?>
<main id="main-container">


    <!-- Wrapper -->
    <div class="content">

<div class="row">

                        <div class="col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">

                            <div class="block">
                                <div class="block-content">


<!-- jQuery Form Validation code -->
<script type="text/javascript" language="JavaScript">
<!--
// verification check

$.validator.addMethod("firstnamev", function (value) {    
    return /^[a-z .]+$/i.test(value)
});
$.validator.addMethod("lastnamev", function (value) {    
    return /^[a-z .]+$/i.test(value)
});

$.validator.addMethod("banknamev", function (value) {    
    return /^[a-z .]+$/i.test(value)
});
$.validator.addMethod("phonenumberv", function (value) { return (value.match(/^((\+)?[1-9]{1,2})?([-\s\.])?((\(\d{1,4}\))|\d{1,4})(([-\s\.])?[0-9]{1,12}){1,2}(\s*(ext|x)\s*\.?:?\s*([0-9]+))?$/)); });


$.validator.addMethod('bankaccountv', function (value) {
       return /^[0-9]+$/.test(value);
}),

// Removes Error Message When reCaptcha is Checked Valid
function recaptchaCallback() {
  $('#hiddenRecaptcha').valid();
};

$(function () {

$("#RegisterForm").validate({
        ignore: ".ignore",

        invalidHandler : function() {
            $('html, body').animate({
                scrollTop: $("#RegisterForm").offset().top // scroll top to your form on error
            }, 'slow' );
        },
        // Specify the validation rules
        rules: {
           bankaccount: { 
                required: true,
                minlength: 7,
                bankaccountv: true,
            },
    phonenumber: { 
                required: true,
                minlength: 7,
                phonenumberv: true,
            },
    firstname: { 
                required: true,
                minlength: 2,
                firstnamev: true,
            },
    lastname: { 
                required: true,
                minlength: 2,
                lastnamev: true,
            },
    bankname: { 
                required: true,
                minlength: 2,
                banknamev: true,
            },
            hiddenRecaptcha: {
                required: function () {
                if (grecaptcha.getResponse() == '') {
                     return true;
                } else {
                     return false;
                }
              }             
           },
       },

        // Specify the validation error messages
        messages: {
            bankaccount: {
                required: "Please enter Bank Account",
                bankaccountv: "Enter valid bank account"
            },
            bankname: {
                required: "Please enter Bank Name",
                banknamev: "Enter valid bank name"
            },
            firstname: {
                required: "Please enter first name",
                firstnamev: "Enter valid Surname"
            },
            lastname: {
                required: "Please enter last name",
                lastnamev: "Enter valid name"
            },
            phonenumber: {
                required: "Please enter Phone Number",
                phonenumberv: "Enter valid phone number"
            },
            submitHandler: function(form) // CALLED ON SUCCESSFUL VALIDATION
            // Redirect can be removed from here
                {
                window.location.replace=''; // Add your custom form submitted redirect page
            }
            // Redirect can be removed to here
        },
   });

});
-->
</script>

<div class="outer-margin">
  <div class="wrapper">
    <!-- Header -->
    <div class="header">&nbsp;Edit Information<br/><br/>
<a href="../resetp.php"> Change Password.</a><br/><br/>
</div>
    <div  class="main">
      <form name="RegisterForm" id="RegisterForm" role="form" action="" method="post" autocomplete="off">
        <?php
       //check for any errors
       if(isset($error)){
           foreach($error as $error){
             echo '<p class="bg-danger">'.$error.'</p>';
           }
       }

         //if action is joined show sucess
$daction = test_input($_GET['action']);
       if(isset($daction) && $daction == 'changed'){
           echo "<div class='bg-success'>Your account information has successfully changed.</div>";
       }
      ?>



 <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="bankaccount">Bank Account</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input name="bankaccount" id="bankaccount" type="text" placeholder="Enter Bank Account" class="form-control" maxlength="50" value="<?php echo $bankaccount;  ?>" tabindex="1">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="bankaccount" generated="true"></label>
          </div>
        </div>
 <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="firstname">First Name</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input name="firstname" id="firstname" type="text" placeholder="Correspond With Your Bank Acct" class="form-control" maxlength="50" value="<?php echo $firstname; ?>" tabindex="1">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="firstname" generated="true"></label>
          </div>
        </div>
 <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="lastname">Last Name</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input name="lastname" id="lastname" type="text" placeholder="Correspond With Your Bank Acct" class="form-control" maxlength="50" value="<?php echo $lastname; ?>" tabindex="1">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="lastname" generated="true"></label>
          </div>
        </div>
 <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="bankname">Bank Name</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input name="bankname" id="bankname" type="text" placeholder="Enter Bank Name" class="form-control" maxlength="50" value="<?php echo $bankname; ?>" tabindex="1">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="bankname" generated="true"></label>
          </div>
        </div>
 <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="phonenumber">Phone Number (+)</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input name="phonenumber" id="phonenumber" type="text" placeholder="Enter Phone Number e.g +13..." class="form-control" maxlength="50" value="<?php echo $phonenumber; ?>" tabindex="1">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="phonenumber" generated="true"></label>
          </div>
        </div>
 <!-- Text input-->
        <div class="input-row">
          <label class="control-label" for="whatsapp">Whatsapp Number (+)</label>
          <div class="inputGroupContainer">
            <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input name="whatsapp" id="whatsapp" type="text" placeholder="Enter Whatsapp Number e.g +13..." class="form-control" maxlength="50" value="<?php echo $whatsapp; ?>" tabindex="1">
            </div>
            <label style="color:red; font-weight:normal;" class="error" for="whatsapp" generated="true"></label>
          </div>
        </div>



<div class="form-group">
                                            <label for="message">Downline message</label>
                                            <textarea class="form-control" name="message"
                                                      style="resize: none;" rows="4" id="message"
                                                      placeholder="Enter message"><?php echo $message; ?></textarea>
                                        </div>





        <!-- NoCaptcha -->
        <div style="display:block; min-height:130px; margin-top:-5px;">
          <label class="control-label" for="hiddenRecaptcha">Security</label>
          <!-- Google No Captcha Human Security Scripts -->
          <input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
          <div class="g-recaptcha" data-sitekey="6Ldujg4UAAAAAN2uBXYSYvGpd2LqPglPlgZ2Fqcx" style="transform:scale(0.90);-webkit-transform:scale(0.90);transform-origin:0 0;-webkit-transform-origin:0 0; color:transparent; font-weight:normal; line-height:0px;" tabindex="5"> </div>
          <div>
            <label style="color:red; font-weight:normal; position:relative; top:-10px;" class="error" for="hiddenRecaptcha" generated="true"></label>
          </div>
        </div>
        <!-- Button -->
        <div class="input-row" style="margin-top:-5px; margin-bottom:-30px;">
          <!-- For sliver button change btn-primary to btn-default - you can add button width:100%; for full width button -->
          <input type="submit" name="submit" value="Save" class="btn btn-primary" tabindex="4">
           </div>
      </form>
    </div>
  </div>
</div>
</div>

   </div></div></div></div>
        </main>
<?php
}
else
{ header('Location: banpage.php'); }  }

//include header template
require('layout/footer.php');
?>

Then, i displayed the data's directly on my webpage without function like below.

$stmt = $db->prepare('SELECT * FROM members WHERE username=:username');
        $stmt->execute(array(':username' => $_SESSION['username']));
while($info = $stmt->fetch(PDO::FETCH_ASSOC)){  

 echo "   
".$info['downlinemsg'] . ""; 

}
\$\endgroup\$
  • 4
    \$\begingroup\$ Please edit your title to summarize the purpose of "this script", and make sure you include all applicable tags. \$\endgroup\$ – Mathieu Guindon Jan 19 '17 at 16:23
  • 4
    \$\begingroup\$ I meant make the title summarize the purpose of your script, not change the title to "summarize the purpose of this script" - basically we want to avoid all php security questions to have a title that says "Is my script safe?" or similar, so we ask that people title their posts with a short summary of what problem their code is solving. \$\endgroup\$ – Mathieu Guindon Jan 19 '17 at 16:37
  • 1
    \$\begingroup\$ In other words, tell us what it does, present it to reviewers. \$\endgroup\$ – Mathieu Guindon Jan 19 '17 at 16:46
  • 1
    \$\begingroup\$ I've updated your title to indicate the purpose of the script. For future reference: here at Code Review we prefer titles which describe what the code does or what you are using it for rather than what you want to see improved. I hope you get good reviews! \$\endgroup\$ – Der Kommissar Jan 19 '17 at 16:51
  • \$\begingroup\$ Damn, that's a lot of code for a few simple forms and form-processing. I'm pretty sure this could get reduced to at most half the size, probably smaller. \$\endgroup\$ – junkfoodjunkie Jan 19 '17 at 22:05
1
\$\begingroup\$

Disclaimer: last time I did PHP was in 2008, take this as a theoretical post rather than a guide.


I would consider trying to extract your php code out to a new file, separate from your HTML code. In fact, I would consider setting up a 'poor man's MVC' (where MVC is Model-View-Controller). The idea with MVC being you have a 'Model' that is used by a 'View' which calls code in a 'Controller'. This way, the bulk of your code can be in the 'Controller' and all you have to do is reference things in the 'Model' inside it. Any major code can go in the model as well.

Your 'Model' would be something like:

public class RegisterViewModel {
    public $error = "";
    public $username = "";
    // Other variables

    public function Build() {
        if (isset($_POST['username'])) {
            $username = $_POST['username'];
        }
        // Etc.
    }
}

Then you would create an AccountController which is something like:

public class AccountController {
    public function GetRegister($registerViewModel) {
        // **Build** the display view model if the user isn't registered

        return $registerViewModel;
    }

    public function PostRegister($registerViewModel) {
        // Now you can act on the values in $registerViewModel to register the user

        return $registerViewModel;
    }
}

Then your Register.php page becomes a view, which would be something like the following:

<?php
    $controller = new AccountController();
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $model = new RegisterViewModel();
        $model.Build();
        $model = PostRegister($model);
    } else {
        $model = GetRegister(new RegisterViewMode());
    }
?>

// Original HTML, but now your error could be `$model.error`, `$model->error` or `$model::error`, or something

My PHP is really rusty, and I never really went this in-depth with it, but this should work fine in theory. The syntax may-or-may-not be valid.

This would entirely separate your code from your display, which is always a good thing. You don't want to have to go through a large chunk of code to find a small display issue you need to tune. Instead you can just open the View.php file, and edit it in there. If you need to alter the actual registration, then it's all in AccountController. Etc.

I've built a sample of the MVC structure on this other question.

\$\endgroup\$
  • \$\begingroup\$ i don't understand the codes you wrote \$\endgroup\$ – General Omosco Jan 19 '17 at 19:29
  • \$\begingroup\$ You might chose to disregard the advice in its entirety. MVC is not a good choice for PHP in general, and those frameworks that use it tend to be clunky. While having separate files for classes, and functions and just use those when needed, php is meant to process HTML, there's no need to add more abstraction. \$\endgroup\$ – junkfoodjunkie Jan 19 '17 at 22:03
  • \$\begingroup\$ @junkfoodjunkie You've obviously never used a good MVC solution. A good MVC solution can hide all the clunkiness entirely. \$\endgroup\$ – Der Kommissar Jan 19 '17 at 22:50
  • \$\begingroup\$ i mine secured, if i used it like that? \$\endgroup\$ – General Omosco Jan 20 '17 at 1:54
  • \$\begingroup\$ any instructions? \$\endgroup\$ – General Omosco Jan 20 '17 at 13:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.