Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- What we will be going over:
- - Secret Token
- - Ajax
- - PHP
- - Unique IDs
- Create a new database.
- [code]
- CREATE TABLE `users` (
- `uuid` VARCHAR(30) UNIQUE,
- `username` VARCHAR(40) UNIQUE,
- `password` VARCHAR(40),
- `email` VARCHAR(255) UNIQUE
- );
- [/code]
- Explination:
- [spoiler]
- UUID = Unique Userd IDs (30 Possible Chars Long), Unique so there can't be a duplicate
- username = Username (40 Possible Chars Long) Unique so there can't be a duplicate
- password = Hashed PW, (40 Possible Chars long because thats the size of the hashed string)
- email = Email, (255 Possible Chars) Unique so ther can't be a duplicate
- [/spoiler]
- Now create a new folder called cfg in your websites root directory. Inside of that create a php file called db.php.
- db.php
- [php]
- <?php
- define('DB_HOST', 'IP OF DB');
- define('DB_NAME', 'DB NAME');
- define('DB_USERNAME', 'DB USERNAME');
- define('DB_PASSWORD', 'DB PASSWORD');
- $odb = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD);
- ?>
- [/php]
- Explination:
- [spoiler]
- define = well, define the info with a string.
- $odb = how we access the database object from now on.
- [/spoiler]
- Now either create or goto your login page and add the follow code to the top
- login.php
- [php]
- <?php
- session_start();
- include 'cfg/db.php';
- if(isset($_SESSION['uuid'])) {
- echo'
- <script language="javascript">
- window.location.href="dashboard.php"
- </script>
- ';
- }
- $token = $_SESSION['token'] = sha1(uniqid(rand(), true));
- ?>
- [/php]
- Explination:
- [spoiler]
- session_start = Starting a PHP Session
- include = We are including the DB code so we can access the PDO object.
- if statment = if there is a SESSION vairable for uuid this means the user is already logged so we forward them to the dashboard.
- token = applies the value of sha1(uniqid(rand(), true)) to the local variable for token and a session variable
- [/spoiler]
- Now create the form and call to the login page.
- login.php
- [php]
- <form id="dankForm">
- <input name="username" type="text" placeholder="Username">
- <input name="password" type="password" placeholder="Password">
- <input name="token" type="hidden" value="<?php echo $token; ?>">
- <input name="submit" type="submit" value="submit">
- </form>
- <script type="text/javascript">
- $("#dankForm").submit(function(e) {
- var url = "cfg/login.php"; // the script where you handle the form input. we'll get to this in a second
- $.ajax({
- type: "POST",
- url: url,
- data: $("#dankForm").serialize(), // serializes the form's elements.
- success: function(data)
- {
- var obj = JSON.parse(data); //parse the json response
- if(obj.status == 'success') {
- window.location.href = "dashboard.php" //redirect to the panel
- } else {
- window.location.href = "login.php?e=" + obj.status; // redirect the user to an error handle
- }
- }
- });
- e.preventDefault(); // avoid to execute the actual submit of the form.
- });
- [/php]
- Explination:
- [spoiler]
- form = REMEMBER THESE NAMES
- script = Ajax call to our login page which validates everything.
- [/spoiler]
- As you probably guessed our next step is to create a login.php in cfg folder.
- cfg/login.php
- [php]
- <?php
- session_start();
- include "db.php";
- $username = $_POST['username'];
- $pass = sha1($_POST['password']);
- $result = $odb -> prepare("SELECT * FROM users WHERE username = :username AND password = :password");
- if($_POST['token'] == $_SESSION['token']) {
- if($result -> execute(array(":username" => $username, ":password" => $pass))) {
- if($result -> rowCount() > 0) {
- $info = $result -> fetch(PDO::FETCH_ASSOC);
- $_SESSION['uuid'] = $info['uuid'];
- $_SESSION['username'] = $info['username'];
- echo json_encode(array("status" => "success"));
- } else {
- echo json_encode(array("status" => "Incorrect Credentials"));
- }
- } else {
- echo json_encode(array("status" => "Database Error"));
- }
- } else {
- echo json_encode(array("status" => "Something weird happened!"));
- }
- ?>
- [/php]
- Explination:
- [spoiler]
- start the session
- include the db object
- get the username from the post array
- get the password from the post array
- check the database for the username and password
- if the token in the post fields and session are the same continue else error out
- if the execute of the query was good continue else error out
- if the number of fields matching are greater than 0 should be 1 contune else error out
- fetch the row into a variable
- create a session var with the name uuid and store it with the info['uuid']
- create a session var with the name username and store it witht he info['username']
- echo a serialized string telling us its all good.
- [/spoiler]
- SWEET! That is all you need for a login, now for the register part!
- Create a file called register.php
- register.php
- [php]
- <?php
- session_start();
- include 'cfg/db.php';
- if(isset($_SESSION['uuid'])) {
- echo'
- <script language="javascript">
- window.location.href="dashboard.php"
- </script>
- ';
- }
- $registerToken = $_SESSION['registerToken'] = sha1(uniqid(rand(), true));
- ?>
- <form id="dankForm">
- <input name="username" type="text" placeholder="Username">
- <input name="password" type="password" placeholder="Password">
- <input name="email" type="email" placeholder="Email">
- <input name="registerToken" value="<?php echo $registerToken; ?>" type="hidden">
- <input name="submit" type="submit" value="submit">
- </form>
- <script type="text/javascript">
- $("#dankForm").submit(function(e) {
- var url = "cfg/register.php"; // the script where you handle the form input. we'll get to this in a second
- $.ajax({
- type: "POST",
- url: url,
- data: $("#dankForm").serialize(), // serializes the form's elements.
- success: function(data)
- {
- var obj = JSON.parse(data); //parse the json response
- if(obj.status == 'success') {
- window.location.href = "login.php" //redirect to the login so he can login.
- } else {
- window.location.href = "register.php?e=" + obj.status; // redirect the user to an error handle
- }
- }
- });
- e.preventDefault(); // avoid to execute the actual submit of the form.
- });
- [/php]
- Explination:
- [spoiler]
- form = REMEMBER THESE NAMES
- script = Ajax call to our register page which validates everything.
- [/spoiler]
- As you probably guessed our next step is to create a register.php in cfg folder.
- cfg/register.php
- [php]
- <?php
- session_start();
- include "db.php";
- $username = $_POST['username'];
- $pass = sha1($_POST['password']);
- $email = $_POST['email'];
- $result = $odb -> prepare("INSERT INTO users VALUES(:uuid, :user, :password, :email)");
- if($_POST['token'] == $_SESSION['token']) {
- if($result -> execute(array(":uuid" => generateUUID($username), ":username" => $username, ":password" => $pass, ":email" => $email))) {
- if($result -> rowCount() > 0) {
- echo json_encode(array("status" => "success"));
- } else {
- echo json_encode(array("status" => "Incorrect Credentials"));
- }
- } else {
- echo json_encode(array("status" => "Database Error"));
- }
- } else {
- echo json_encode(array("status" => "Something weird happened!"));
- }
- private function generateUUID($username) {
- $randomString = "";
- $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
- $charactersLength = strlen($characters);
- for ($i = 0; $i < (strlen($username) - 40); $i++) {
- $randomString .= $characters[rand(0, $charactersLength - 1)];
- }
- return $username . $randomString;
- }
- ?>
- Explination:
- [spoiler]
- start the session
- include the db object
- get the username from the post array
- get the password from the post array
- prepare to insert into the database
- if the token in the post fields and session are the same continue else error out
- if the execute of the query was good continue else error out
- echo a serialized string telling us its all good.
- Generate UUID Function:
- Initalize a new empty variable
- Field of chars
- Get length of chars string
- while i is less than 40(uuid max size) - username length
- append
- return
- [/spoiler]
Add Comment
Please, Sign In to add comment