Search code examples
phpsession-cookies

How secure are PHP sessions?


I'm primarily a C++ programmer, but I'm trying to pick up some PHP.

Apparently the way to implement web user sessions is to store the user's login ID in a cookie using the $_SESSION variable.

Is it not possible for someone to just modify their cookie, to give them different privileges or log in as a different user?

It seems like this authentication mechanism is just having the user store their ID in a file - and then just trusting them not to change it.

Is there something that prevents this?

Thanks!


Solution

  • No, a session is stored on the server and cannot be accessed by the user. It is used to store information across the site such as login sessions.

    Here is an example of the usage:

    <?php
    session_start();
    if (password_verify($_POST['password'], $hash)) {
        $_SESSION['auth'] = true;
    }
    ?>
    

    The session can then be accessed across the site to check to see if the user has been authenticated.

    <?php
    session_start();
    if ($_SESSION['auth']) {
        echo "You are logged in!";
    }
    ?>
    

    The user cannot edit these values however the session's ID is stored on a computer through a cookie as a long random string. If an unauthorized user gains access to these strings it is possible for them to access the site.