DB structures

3. Read user-file

Step 1: Creating a user.txt

  1. Create a file:
  • Create a file called user.txt and put it in the folder where all your other files are.

    stefan,mypass,standarduser
    bao,bao,admin
    Janek,password456,admin
    Noel,noel,superdude
  1. Read data from a file:
  • So now we have a file with users but we need to read the file to an array so we can check if your user data actually is correct.

    $users = [];   // Create an array
    $file =fopen('users.txt', 'r');   // Open the fie
    while(!feof($file)){  // Reading until eof (End of file)
     array_push($users,fgetcsv($file));  // Reading one row at a time and store it into the user.   
    }
    fclose($file);  // Close the file
    );
  1. Check the login
  • So now we have the userlist in an array we can now check the set value of $_POST['usernamne'] and POST['password'] and see if the credentials are correct.
    
    // Check if you are trying to loggin
    if(isset($_POST['loginname']) && isset($_POST['password'])){
    $username = $_POST['loginname'];
    $password = $_POST['password'];
    // Check if the input data actually is a user or not
    $loggedin=false;
    foreach($users as $user){
       if($user[0] === $username && $user[1] === $password){
           $loggedin=true;
           $_SESSION['loggedin'] = true;
           $_SESSION['role'] = $user[2];
           $_SESSION['username'] = $username;
       }
    } 
    if(!$loggedin){
           header('Location: hell.html');
       exit;
    }
    }