Php login page function with database and user session

Login form is the important part for each developer when a website ask the users to sign up. Once the sign up process is done by filling up the registration form, website send an verification email to the user on the email to verify account. Once the verification is successfully completed via email! User has to to sign in through the website to access the additional features in website e.g Post an article or Commenting basically when it comes to developers blog.

Php login form function using session

  • Let's check how function loginUser handles the login session.

In function loginUser we are passing two parameters "emai id" as username and "password". Fetching the parameters in function "loginUser" encrypts the password using md5 encryption function. $str is the variable declared with the "ERR" message as default so if the username and password goes wrong it won't return true.

Using mysql select query, PHP function checks whether the username and the password is valid or not in mysql "wd_users" table. As the result is fetched using mysql_query function, it checks for the number of rows which should be greater then 0 = "NULL" using mysql_numrows(). If the number of rows are greater then 0 then variable are extracted from the result using mysql_fetch_array().

Now let's see how the session variable are declared and how the values are stored in session variable.

  • Note : If you are declaring session variable it is important to start the session using session_start() placed above the line of first session variable declared.

Looking into the session variables we are storing userID, name and email values respectively.

  • Declaring session variables
  • "User ID" as $_SESSION['SITEUSERID']
  • "Username(fullname)" as $_SESSION['SITEUSERNAME']

Once the values are stored respectively in session variables! $str is return as true with err msg "LOGGED" which means the user is logged in and the user session is active in the browser.


function loginUser($email,$password){
    $password = md5($password); 
    $str = "ERR";
    $query = "SELECT * FROM wd_users WHERE email='".mysql_real_escape_string($email)."' AND password='".mysql_real_escape_string($password)."'";
    $results = mysql_query($query);
    if (mysql_numrows($results)) {
        $arr = mysql_fetch_array($results);
        $_SESSION['SITEUSERID'] = $arr['userID'];
        $_SESSION['SITEUSERNAME'] = $arr["name"];
        $_SESSION['SITEUSEREMAIL'] = $arr["email"];
        $str = "LOGGED";
    }else {
        $str = "WRONG";
return $str;


login form sessionsession login and logoutsession login page in phpsession login php mysql simple php login sessionsimple php login session