3
\$\begingroup\$

I try to dealing with sessions.. including arrays before moving to "database".

Sessions class.file

<?php
session_start();
class Sessions {


public static function ready($name){
  return isset($_SESSION[$name]) ? true : false;
}
    public static function get($name){
      if(isset($_SESSION[$name])){
        return $_SESSION[$name];
      }else {
        return false;
      }
      }

public static function set($name, $val = []){
  return $_SESSION[$name] = $val;

}

    public static function des($name){
      if(self::ready($name)){
       unset($_SESSION[$name]);
      }

    }

}

index.php file

<?php

include_once "Sessions.php";

const BR = '<br>';

$er = [];
$data = array([
    'id'=> '1',
    'username'=> 'user1',
    'password'=>'123456'
  ],
  [
    'id'=> '2',
    'username'=> 'user2',
    'password'=>'654321'
  ]
);

//submit
if(isset($_POST['submit'])){
  // Error Msgs
$er[] = "Not found in array";
// Forms Inputs
$username = $_POST['username'];
$password = $_POST['password'];

//fetch users in array
foreach ($data as $key => $value) {
  if(in_array($username, $value)){
    if( $username == $value['username'] && $password == $value['password'] ){
      $uid = $value['id'];
      $unm = $value['username'];
      //Sessions class
      Sessions::set('id', $uid);
      Sessions::set('username', $unm );
      // Error Msgs
     unset($er[0]);
    }
}
  }
}


?>
<?php
//Sessions class
$susername = Sessions::ready('username');
$sid = Sessions::ready('id');
if( $susername AND $sid) { ?>
<?$sid?>
<?$susername?>
<?=BR.Sessions::get('username').BR?>
<?=BR.Sessions::get('id').BR?>
<br>
<a href='log.php'>Out</a>
<br>
<? if( isset( $er[0] ) ) { echo $er[0];}else { unset( $er[0] ); } ?>

<form  method="post">
  <input type="text" name="username" value="">
  <input type="password" name="password" value="">
  <input type="submit" name="submit" value="submit">
</form>

logout.php file

<?php
include_once "Sessions.php";
Sessions::des('username');
Sessions::des('id');
header("Location:session.php");
?>

Is it good for beginner..! is there something wrong..! is there better way for that messy code ?

\$\endgroup\$
0
\$\begingroup\$
  • return isset($_SESSION[$name]) ? true : false; is more succintly written as:

    return isset($_SESSION[$name]);
    

    The boolean evaluation of isset() is all you need.

  • You can use the null coalescing operator to tight up:

    if(isset($_SESSION[$name])){
        return $_SESSION[$name];
    }else {
        return false;
    }
    

    Into:

    return $_SESSION[$name] ?? false;
    
  • You never need to check if a variable exists before calling unset(). If the variable doesn't exist, the script smoothly, silently continues processing as usual.

  • The tabbing of your code is needing a fair amount of tender loving care. Use 4 spaces to indent where necessary. PSR standards are available for everyone's benefit.

  • I don't think I support the technique of pushing an error message into an array pre-emptively, then removing the element if everything passes. Add a descriptive error to the error array ONLY if an error is detected.

  • If you are not going to use a variable (e.g. $key in your loop), then don't bother declaring it.

  • I realize this is just practice, but try to store only id values in session data if your project permits it. There is such a thing as Session Hijacking -- it may be an extreme scenario, but it is best to avoid storing any "real world" identifying data in session arrays.

  • I generally avoid using AND and OR in my if expressions so that I am never tripped up by a fringe "precedence" gotcha.

  • If you want to display boolean values for diagnostics, I recommend var_export().

  • Finally, read about how to destroy a session on logout: PHP Session Destroy on Log Out Button

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.