-1

I am new to PHP and have been making a login system for my website. I am unsure of how I should be handling sessions with my current code, and am just looking for some advice on how to do so.

Here is my User class:

<?php

include_once('connection.php'); 

class User{

    private $db;

    public function __construct(){
        $this->db = new connection();
        $this->db = $this->db->dbConnect();
    }

    public function Login($username, $password){

        if(!empty($username) && !empty($password)){

            $st = $this->db->prepare("SELECT * FROM users WHERE username =? AND password=?");
            $st->bindParam(1, $username);
            $st->bindParam(2, $password);

            $st->execute();

            if($st->rowCount() == 1){
                header('location: userHome.php');
            }
            else{
                echo "Incorrect username or password";
            }
        }
        else{
            echo "Please enter your username and password";
        }
    }

    public function Register($username, $password, $email){

        if(!empty($username) && !empty($password) && !empty($email)){

            $st = $this->db->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");

            $st->bindParam(1, $username);
            $st->bindParam(2, $password);
            $st->bindParam(3, $email);

            $result = $st->execute();

            if($result){
                echo("Success. You have been registered");
            }
            else{
                echo("There has been a problem. Please try again");
            }
        }
        else{
            echo "Please fill in all of the fields";
        }
    }
}

?>

And here is my connection class:

<?php

class connection{

    private $db_host = 'omitted',
            $db_name = 'omitted',
            $db_username = 'omitted',
            $db_pass = 'omitted';

    public function dbConnect(){

        try
        {
            return new PDO("mysql:host=".$this->db_host.';dbname='.$this->db_name, 
                            $this->db_username, $this->db_pass);
        }
        catch(PDOException $e){

            $e->getMessage();
        }
    }
}

?>

And here is my index.php file where the user logs in:

<?php
    include_once('user.php');

    if(isset($_POST['submit'])){

        $username = $_POST['username'];
        $password = $_POST['password'];

        $object = new User();
        $object->Login($username, $password);
    }
?>

<html>

<head>
    <link rel="stylesheet" type="text/css" href="css/layout.css">
</head>

<body>

    <div id="form-container">
        <h2>Login</h2>
        <form method="post" action="index.php">
            <label for='username'>Username: </label>
            <input type="text" name="username"/><br>
            <label for='password'>Password: </label>
            <input type="password" name="password"/><br>
            <input type="submit" value="Submit" id="button" name="submit"/>
        </form>
        <br>
        <a href="register.php">Register Here</a>
    </div>

</body>

</html>

I have been stuck on how to tackle handling sessions with my current code for a while now, and any suggestions will be much appreciated.

Thank you.

  • There's nothing to it, really, you just use `session_start()` directive on the file that's the "master file" of you code and you're sorted. Al you have to do after is save stuff to it by `$_SESSION['wtv'] = "value";` [Tizag explains this easy enough](http://www.tizag.com/phpT/phpsessions.php) – MoshMage Aug 24 '14 at 08:56
  • [OT] You should learn about and use a proper [doctype](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Introduction#Doctype_and_comments) for your HTML, this will define in which way your HTML is showed – mTorres Aug 24 '14 at 09:07

1 Answers1

2

Initialize the session

Ok, I would firstly add a session start at the top of user.class.php and index.php. To prevent calling session_start() more than once, use this code:

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

Add values to the session superglobal

In your login function:

if($st->rowCount() == 1){
    $_SESSION['login'] = 'true';
    $_SESSION['username'] = $username;
    header('location: userHome.php');
}

Give your website a user-specific experience

You can easily go to your index.php page and display content only for logged in users:

if($_SESSION['status'] == 'true') {
    echo 'Username: <b>'.$_SESSION['username'].'</b>';
} else {
    //your login form
}

In my code, I also have saved the email into a session variable, if you want you can query the user's email from the database.

Additional notes

Btw, to check if a post is submitted, I advise you to use: (reference)

if($_SERVER['REQUEST_METHOD'] == 'POST')
Community
  • 1
  • 1
Jacob T
  • 21
  • 3
  • Side note, you don't need to test if a boolean value is ```== 'true'``` after all what a *if* needs is a boolean value so ```if ($_SESSION['status']) {``` is enough. Also if you change the key name you have: ```if ($_SESSION['isLoggedIn']) {``` which is selfexplanatory :-) – mTorres Aug 24 '14 at 09:10
  • If you ask `if($_SESSION['status'])` and you are not logged in you will get **Notice: Undefined index**. – Jacob T Aug 24 '14 at 09:15
  • Thank you that's very helpful. How would I handle logging out? Would I have a new file that destroys the session? – user2985945 Aug 24 '14 at 09:15
  • @JacobT this is because you're using a string: ```'true'```. Real boolean values are not enclose withing quotes: ```$someBoolVar = true```. Keep in mind that a non empty string casted as a boolean is always true, so if you have ```$someVar = 'false' //this is a string!``` and check ```if ($someVar) { // do something }``` this will always be evaluated to true as only an empty string is evaluated to false. See the [manual](http://php.net/manual/en/language.types.boolean.php) for more info. End of OT now :-) – mTorres Aug 24 '14 at 09:21
  • No, do that in your user class! http://stackoverflow.com/questions/1226040/is-this-a-proper-way-to-destroy-all-sessions-in-php – Jacob T Aug 24 '14 at 09:22
  • @mTorres. I used booleans for a very long time and I had this problem with undefined index, so I switched to a string. $_SESSION['login'] is not defined until the user is logged in – Jacob T Aug 24 '14 at 09:25
  • Well, in xampp I get this notice every time, but not on my server. Is there a shorter method to see if a variable is already set and true? – Jacob T Aug 24 '14 at 09:27
  • You can check for that in a two condition if: ```if (isset($_SESSION['login']) && $_SESSION['login']) { // do something }```. Also check your code, you're setting ```$_SESSION['login']```, but the you're checking ```$_SESSION['status']```, you'll never detect a true logged user :-) – mTorres Aug 24 '14 at 09:29
  • I meant $_SESSION['status'], sorry. I asked for a "shorter method", this one is obvious of course – Jacob T Aug 24 '14 at 09:31
  • AFAIK there is no shorter way (well you could create an object session and in a get method you can check if a key isset and its value, but in your client code you'll only need to call ```$mySession->get('key')```), but you'll have the same problem with strings also, if it's not set in the array, you cannot check its value (PHP should yeld a notice), you'll need to make sure isset and then you can check the value... – mTorres Aug 24 '14 at 09:37