Facebook
From andja, 9 Months ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 468
  1. function.php///////////
  2.  
  3.  
  4. <?php
  5. session_start();
  6. $conn = mysqli_connect("localhost", "root", "", "loginregister");
  7.  
  8. // IF
  9. if(isset($_POST["action"])){
  10.   if($_POST["action"] == "register"){
  11.     register();
  12.   }
  13.   else if($_POST["action"] == "login"){
  14.     login();
  15.   }
  16. }
  17.  
  18. // REGISTER
  19. function register(){
  20.   global $conn;
  21.  
  22.   $name = $_POST["name"];
  23.   $username = $_POST["username"];
  24.   $password = $_POST["password"];
  25.  
  26.   if(empty($name) || empty($username) || empty($password)){
  27.     echo "Please Fill Out The Form!";
  28.     exit;
  29.   }
  30.  
  31.   $user = mysqli_query($conn, "SELECT * FROM tb_user WHERE username = '$username'");
  32.   if(mysqli_num_rows($user) > 0){
  33.     echo "Username Has Already Taken";
  34.     exit;
  35.   }
  36.  
  37.   $query = "INSERT INTO tb_user VALUES('', '$name', '$username', '$password')";
  38.   mysqli_query($conn, $query);
  39.   echo "Registration Successful";
  40. }
  41.  
  42. // LOGIN
  43. function login(){
  44.   global $conn;
  45.  
  46.   $username = $_POST["username"];
  47.   $password = $_POST["password"];
  48.  
  49.   $user = mysqli_query($conn, "SELECT * FROM tb_user WHERE username = '$username'");
  50.  
  51.   if(mysqli_num_rows($user) > 0){
  52.  
  53.     $row = mysqli_fetch_assoc($user);
  54.  
  55.     if($password == $row['password']){
  56.       echo "Login Successful";
  57.       $_SESSION["login"] = true;
  58.       $_SESSION["id"] = $row["id"];
  59.     }
  60.     else{
  61.       echo "Wrong Password";
  62.       exit;
  63.     }
  64.   }
  65.   else{
  66.     echo "User Not Registered";
  67.     exit;
  68.   }
  69. }
  70. ?>
  71.  
  72. index.php/////////
  73.  
  74.  
  75. <?php
  76. require 'function.php';
  77. if(isset($_SESSION["id"])){
  78.   $id = $_SESSION["id"];
  79.   $user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM tb_user WHERE id = $id"));
  80. }
  81. else{
  82.   header("Location: login.php");
  83. }
  84. ?>
  85. <!DOCTYPE html>
  86. &lt;html lang="en" dir="ltr"&gt;
  87.   &lt;head&gt;
  88.     &lt;meta charset="utf-8"&gt;
  89.     &lt;title&gt;Index&lt;/title&gt;
  90.   &lt;/head&gt;
  91.   &lt;body&gt;
  92.     <h1>Welcome &lt;?php echo $user["name"]; ?&gt;</h1>
  93.     <a href="logout.php">Logout</a>
  94.   &lt;/body&gt;
  95. &lt;/html&gt;
  96.  
  97.