DEV Community

Ashish
Ashish

Posted on

My First PHP Reg[Worst Starter Code]

Hello All,
I just tried a Small PHP code.
The Point Here is not Best Practices or Clean Code.
But To remind me when i come back to this Post that
ohhh!! I did this and How different code i have written after a span of time.

This is Just for Reference

Anyone Who has a Better Snippet, Please add it to the comment,
For Me as well as for Others to Keep a Note

Well Usually will not add this: ->
SET utf8mb4 COLLATE utf8mb4_unicode_ci
But Since I Copied it From a Project, I Though Let's keep it this Way

Table for the Below PHP MySQL Insertion

// Table

CREATE TABLE `reg_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `level` smallint(6) NOT NULL DEFAULT 1,
  `user_name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `full_name` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `password_hash` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `email_address` varchar(75) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `timestamp` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `last_login` int(11) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_name` (`user_name`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4

Enter fullscreen mode Exit fullscreen mode

Registration PHP Code:

<?php

/*** I Have NO Clue But I will Try To Investigate on it Later: 
Well My Point was to Get the PHP Debugging Logs: 
`It does Not works`
But I will Figure it Out Soon
****/

error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");

/*** Unknown Code Ends Here ***/

// Get The Request Method
$request_method = $_SERVER["REQUEST_METHOD"];

//  Only Process if POST
if ($request_method == "POST") {

  // Collect Value of Post Body In PHP Variables
  $fullname = $_POST['fullname'];
  $username = $_POST['username'];
  $emailaddress = $_POST['emailaddress'];
  $password1 = $_POST['password1'];
  $password2 = $_POST['password2'];  

  // Validate and then Call the DB Action
  if( validate_inputs($fullname, $username, $emailaddress, $password1, $password2) ) {
        # Quick Password Hash
    $password_hashed = password_hash($password1, PASSWORD_DEFAULT);
    db_action($fullname, $username, $emailaddress, $password_hashed);
  }

} else {
    echo "In Correct Method: [{$request_method}]";
}

// Check, Confirm and Add to MySQL Database
function db_action($fullname, $username, $emailaddress, $password_hashed) {

    $db_host="localhost"; //localhost server 
    $db_user="temp"; //database username
    $db_password='temp@55hh778_0!'; //database password   
    $db_name="temp_db"; //database name

    try
    {
      $dsn = "mysql:host={$db_host};dbname={$db_name}";
      $options = [
        PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
      ];
      $db=new PDO($dsn,$db_user,$db_password, $options);
      $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

      // Check First
      $check_statement = $db->prepare('SELECT * FROM jam_reg_users where user_name=:user_name LIMIT 1 ');

      $check_statement->execute([
        'user_name' => $username
      ]);

      $is_user_exists = $check_statement->fetch();

      if ($is_user_exists) {
          die("[+] User Exists, Please Use Another User");
      } else {
          //die("[-]User DOES NOT Exists");

          $insert_statement = $db->prepare('INSERT INTO jam_reg_users (user_name, full_name, password_hash, email_address, timestamp) VALUES (:user_name, :full_name, :password_hash, :email_address, :timestamp)');

          $insert_statement->execute([
            'user_name' => $username,
            'full_name' => $fullname,
            'password_hash' => $password_hashed,
            'email_address' => $emailaddress,
            'timestamp' => date("Y-m-d H:i:s",time())
          ]);

          echo "User Added, Please Login Here <a href='http://login.local/'> Login Here </a>";
      }

    }
    catch(PDOEXCEPTION $e)
    {
      $e->getMessage();
      error_log($e->getMessage());
      exit('Exception Caught Here');
    }

}

// It will Check for Fields Received in Post Body and Validate If it Empty, Blank or Not Present

function validate_inputs($fullname, $username, $emailaddress, $password1, $password2) {

  $fullname_pass = false;
  $username_pass = false;
  $emailaddress_pass = false;
  $password1_pass = false;
  $password2_pass = false;

  if ( empty($fullname) || $fullname === "" || trim($fullname," ") === "" ) {
    echo "Full Name Not Found";
  } else {
    $fullname_pass = true;
  }

  if ( empty($username) || $username === "" || trim($username," ") === "" ) {
    echo "Username Not Found";
  } else {
    $username_pass = true;
  }

  if ( empty($emailaddress) || $emailaddress === "" || trim($emailaddress," ") === "" ) {
    echo "Email Address Not Found";
  } else {
    $emailaddress_pass = true;
  }

  if ( empty($password1) || $password1 === "" || trim($password1," ") === "" ) {
    echo "Password Not Found";
  } else {
    $password1_pass = true;
  }

  if ( empty($password2) || $password2 === "" || trim($password2," ") === "" ) {
    echo "Re-Enter Password Not Found";
  } else {
    if ( $password1 === $password2 ) {
      $password2_pass = true;
    } else {
        echo "Password Did Not Match";
    }
  }

  if ($fullname_pass && $username_pass && $emailaddress_pass && $password1_pass && $password2_pass) {
      return true;
  } else {
      return false;
  }
}

?>



Enter fullscreen mode Exit fullscreen mode

I saw a Better Code
I will Add it Soon.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.