· 9 years ago · Nov 01, 2016, 08:16 PM
1//login.php
2<?php
3require_once 'dbconnect.php';
4use \Firebase\JWT\JWT;
5define('SECRET_KEY','s25cLeE3205q4UwNG39ENX4lDGN63awS');
6define('ALGORITHM','HS512');
7
8 $username = !empty($_POST['username']);
9 $pass = !empty($_POST['password']);
10
11 // if there is no error below code run
12 $statement = $conn->prepare("select * from users where username = :username" );
13 $statement->execute(array(':username' => $username));
14 $row = $statement->fetchAll(PDO::FETCH_ASSOC);
15 $hashAndSalt = password_hash($password, PASSWORD_BCRYPT);
16 if(count($row)>0 && password_verify($row[0]['password'],$hashAndSalt))
17 {
18 $tokenId = base64_encode(mcrypt_create_iv(32));
19 $issuedAt = time();
20 $notBefore = $issuedAt + 10; //Adding 10 seconds
21 $expire = $notBefore + 60; // Adding 60 seconds
22 $serverName = 'localhost'; /// set your domain name
23
24
25 /*
26 * Create the token as an array
27 */
28 $data = [
29 'iat' => $issuedAt, // Issued at: time when the token was generated
30 'jti' => $tokenId, // Json Token Id: an unique identifier for the token
31 'iss' => $serverName, // Issuer
32 'nbf' => $notBefore, // Not before
33 'exp' => $expire, // Expire
34 'data' => [ // Data related to the logged user you can set your required data
35 'id' => $row[0]['id'], // id from the users table
36 'name' => $row[0]['name'], // name
37 ]
38 ];
39 $secretKey = base64_decode(SECRET_KEY);
40 /// Here we will transform this array into JWT:
41 $jwt = JWT::encode(
42 $data, //Data to be encoded in the JWT
43 $secretKey // The signing key
44 );
45 $unencodedArray = ['jwt' => $jwt];
46 echo json_encode($unencodedArray);
47 } else {
48 echo "{'status' : 'error','msg':'Invalid email or password'}";
49 }
50
51?>