4
\$\begingroup\$

I created a simple login system using just sessions but having to login every time gets annoying. That is why I'm no trying to save the sessions to my database linked to the user's account. I will first show my code and than ask a few questions.

First file which is the new file I created is this one named sessiontest.php

<?php 
session_start();
include($_SERVER['DOCUMENT_ROOT']. '/../db_connect.php');

if (!Isset($_SESSION['crecketgaming_usergroup'])){
    $_SESSION['crecketgaming_usergroup'] = "Guest";
}
    try {
        $conn = new PDO("mysql:host=$servername:3307;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE,  PDO::ERRMODE_EXCEPTION);
    }catch(PDOException $e){
    }

mainCheck($conn);
function mainCheck($conn){
    $session_id = "";
    if(isset($_COOKIE['Crecketgaming_sessionid'])){
        $time = time();
        $session_id = $_COOKIE['Crecketgaming_sessionid'];
        $addrip = $_SERVER['REMOTE_ADDR'];
        $userid = $_SESSION['crecketgaming_userid'];
        $sql = "SELECT * FROM sessions WHERE session_id = :sessionid AND ip = :addrip"; 
        $sth = $conn->prepare($sql);
        $sth->bindParam(':sessionid', $session_id, PDO::PARAM_STR);
        $sth->bindParam(':addrip', $addrip, PDO::PARAM_STR);
        $sth->execute();
        $rowcount = $sth->rowCount();
        $row = $sth->fetch();   
        $userid = $row['user_id'];  
        if ($rowcount > 0) {
            setSessionDetails($conn, $userid)
        } else {
            $session_id = storeUID($conn);
        }
    } else {
        $session_id = storeUID($conn);
    }

    if($session_id == "") {

    } else {

        setSessionDetails($conn, $userid);
}
    }


function storeUID($conn){
    $addrip = $_SERVER['REMOTE_ADDR'];
    $userid = $_SESSION['crecketgaming_userid'];
    $session_id = createUID(100);
    $time = time();
    if(setcookie("Crecketgaming_sessionid", $session_id, mktime(). time()+60*60*24*30)){
        $agent = $_SERVER['HTTP_USER_AGENT']; 
        $ip = $ip = $_SERVER['REMOTE_ADDR'];
        $sql = "INSERT INTO sessions (user_id, session_id, ip, time) VALUES (:userid, :sessionid, :addrip, :time)";
        $sth = $conn->prepare($sql);
        $sth->bindParam(':userid', $userid, PDO::PARAM_STR);
        $sth->bindParam(':sessionid', $session_id, PDO::PARAM_STR);
        $sth->bindParam(':addrip', $addrip, PDO::PARAM_STR);
        $sth->bindParam(':time', $time, PDO::PARAM_INT);
        $sth->execute();
    }
    return $session_id;
}

function createUID($length) {
    $chars = "abcdefghijkmnopqrstuvwxyz0123456789"; 
    srand((double)microtime()*1000000); 
    $i = 0; 
    $pass = '' ;
    while ($i < $length) { 
        $num = rand() % 33; 
        $tmp = substr($chars, $num, 1); 
        $pass = $pass . $tmp; 
        $i++; 
    }
    return $pass;
}

function setSessionDetails($conn, $userid) {
    session_start($session_id);
    session_id($session_id);
    $sql = "SELECT Usergroup, user_ID FROM users WHERE Username = :username";
    $sth = $conn->prepare($sql);
    $sth->bindParam(':username', $userid, PDO::PARAM_STR);
    $sth->execute();
    $row = $sth->fetch();   

    $_SESSION['crecketgaming_usergroup'] = $row['Usergroup'];
    $_SESSION['crecketgaming_username'] = $row['Username'];
    $_SESSION['crecketgaming_userid'] = $row['user_ID'];
}

Second part is the file I used in my old system, it sets a bunch of session variables and its kind of a mess right now.

<?php       
try {
    $conn = new PDO("mysql:host=$servername:3307;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE,  PDO::ERRMODE_EXCEPTION, PDO::ERRMODE_SILENT);
}catch(PDOException $e){
}
include('/includes/sessiontest.php');

if (!Isset($_SESSION['crecketgaming_usergroup'])){
    $_SESSION['crecketgaming_usergroup'] = "Guest";
}

if (Isset($_SESSION['crecketgaming_username'])){
    $usernametest = $_SESSION['crecketgaming_username'];
    $sql2 = "SELECT Usergroup, user_ID FROM users WHERE Username = :username"; 
    $sth = $conn->prepare($sql2);
    $sth->bindParam(':username', $usernametest, PDO::PARAM_STR);
    $sth->execute();
    $rowcount = $sth->rowCount();
    $row = $sth->fetch();       

    if ($rowcount > 0) {
        $_SESSION['crecketgaming_usergroup'] = $row['Usergroup'];
        $_SESSION['crecketgaming_userid'] = $row['user_ID'];
    }
    $_SESSION['crecketgaming_loginmessage'] = "
        <form class='s-12 l-12 shadow profbox' method='post' action='logout.php' >
            <div class='line'>
                <div class='margin-bottom'>
                    <div  align='center' class='s-12 l-12'>
                        <a>You're currently logged in as: <br><strong>" . $_SESSION['crecketgaming_username'] . "</strong> " . $_SESSION['crecketgaming_usergroup'] . "  </a>
                        <br>
                    </div>
                </div>
            </div>
        </form>
    ";
    if($_SESSION['crecketgaming_usergroup'] == "Admin"){
        $_SESSION['crecketgaming_menuadmin'] = '    
            <li>
                <a>Adminpanel</a>
                <ul>
                    <li><a href="/phpadmin/adminpanel">Main panel</a></li>
                    <li><a href="/phpadmin/checkusers">Users</a></li>
                    <li><a href="/phpadmin/checkreloads">Page loads</a></li>
                    <li><a href="/phpadmin/checklocked">Locked accounts</a></li>
                    <li><a href="/phpadmin/checksessions">Sessions</a></li>
                    <li><a href="/phpadmin/checkfailed">Failed logins</a></li>
                    <li><a href="/phpadmin/checkactivation">Activate accounts</a></li>
                    <li><a href="/blogpost">New blog post</a></li>
                </ul>
            </li>
            ';
    }else{
        $_SESSION['crecketgaming_menuadmin'] = '';
    }
    $_SESSION['crecketgaming_profileicon'] = 'class="icon-user_male icon2x right padding"';
    $_SESSION['crecketgaming_menuaccount'] =  '<li><a>Account</a><ul><li><a href="/profile">My profile</a></li><li><a href="/logout">Logout</a></li></ul></li>';
    $_SESSION['crecketgaming_webshopmessage'] = "<li><a>Market</a><ul><li><a href='index.php'>Market</a></li><li><a href='profile?userid=" . $_SESSION['crecketgaming_userid'] . "'>My profile</a></li><li><a href='newsale'>New/Change sale</a></li></ul></li>";
}elseif (!Isset($_SESSION['crecketgaming_username']) || $_SESSION['crecketgaming_username'] = "" ) {
    $_SESSION['crecketgaming_webshopmessage'] = "<li><a href='index.php'>Market</a></li>";
    $_SESSION['crecketgaming_loginmessage'] = "
    <a href='login.php'>
        <div class='s-12 l-12 shadow profbox'>
            <div class='line'>
                <div class='margin-bottom'>
                    <p align='center'>You are currently not logged in.</p>
                </div>
            </div>
        </div>
    </a>
    ";
    $_SESSION['crecketgaming_profileicon'] = "";
    $_SESSION['crecketgaming_menuadmin'] = "";
    $_SESSION['crecketgaming_menuaccount'] =  '<li><a>Account</a><ul><li><a href="/login">Login</a></li> <li><a href="/register">Register</a></li></ul></li>';
    $_SESSION['crecketgaming_usergroup'] = "Guest";
    $_SESSION['crecketgaming_userid'] = "";
}

In my login.php file I would only check for the current session and than add the userid to that row.

Is this a secure way to do this? Or do I need to create a complete new id? Also is this script even any good? This script isn't working 100% yet but I'm sure its atleast close, as of now I'm just kind of stuck

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Naming I recommend to name vars in camelCase and use the datatype as prefix. The former provides a better reading while the latter let the current developer know what kind of datatype this var holds.

Procedural vs Oop The procedural programming style is a good start for beginner but oop aka object oriented programming is the better way to go. Even though it takes time to get into it and it seems to be overhead sometimes it more or less provides scalable software (depends on more aspects) which procedural does not. If oop is new to you may use your favourite search engine to read more about it.

Logic & View You are mixing software logic (php part) with the view (html). In general this should be avoided. They rather have to be seperated. Doing this increase the scalability as well. For further details check patterns such as the well-known mvc-pattern. Mvc is the abbreviation for model view controller.

Exceptions In the file sessiontest.php you catch an exception without further handling. This is dirty and shouldn't be done. Don't get me wrong. It's good to catch exceptions but they should be fully handled. Just to name one example. You could write a log message to a specific file and print a simple message for the user such as "Sorry, something went wrong. We take care of that."

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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