Session_start help needed

Username (e.g. epiz_XXX) or Website URL

(please specify the website or account you are asking about)

If someone could help me with the correct PHP coding to prevent access to a page unless I’m logged in, it would be greatly appreciated.

I have a number of forms on my site that I want to restrict access to unless user (Admin) is logged in.
From articles/tutorials I’ve read, I believe this can be achieved by using “session_start(); but cannot get the example PHP codes from the articles/tutorials to produce the results I’m after.
Example - Cue Well Snooker (epizy.com) should only be accessible after login, but it’s not. Anyone knowing the URL can load the page, and then fill and submit the form and data gets inserted into my db. Not good. I want to control who can access my forms.
Currently I have a “login” table in my db with username/password for 1 user. Me : )
This is a list of files I’ve been working on and I’ve provided code for most below to help you understand.

  1. config/auth.php
  2. config/config.php
  3. config/login.php
  4. config/session.php
  5. login-failed.php
  6. record-friday-results.php

config.php – This file has my database details, creates connection, and checks if connection is working or not.
I have tested the config.php file and can see “Success” or “Fail” message, so all works fine using config.php

login.php – If login credentials match database, user is redirected to record-friday-results.php -
Cue Well Snooker (epizy.com)
If login credentials DO NOT match database, user is redirected to login-failed.php - Cue Well Snooker (epizy.com) so all works fine.
The login form can be seen here - Cue Well Snooker (epizy.com) or form code seen below.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Cue Well Snooker</title>
<link rel="icon" type="image/x-icon" href="/images/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Link css file -->
    <link href="../css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
    <div class="header">
        <!-- Logo -->
        <a href="../index.php" class="logo"><img src="../images/cws.png" style="border: 0px"></a>
</div>
<?php require_once('../navbar.php'); ?>
<!-- Container -->
<div class="container">
<div class="formcontainer">
<h2>Login Required</h2>
<!-- <h3>to record Friday night results</h3> --> 
        <form name="f1" action = "auth.php" onsubmit = "return validation()" method = "POST">	
		<input type = "text" id ="user" required placeholder="User Id" name  = "user" />
		<input type = "password" id ="pass" required placeholder="*********" name  = "pass" />
		<input type="submit" value="LOGIN" name="insert">
		</form>
</div>
</div>
    <script>  
            function validation()  
            {  
                var id=document.f1.user.value;  
                var ps=document.f1.pass.value;  
                if(id.length=="" && ps.length=="") {  
                    alert("User Name and Password fields are empty");  
                    return false;  
                }  
                else  
                {  
                    if(id.length=="") {  
                        alert("User Name is empty");  
                        return false;  
                    }   
                    if (ps.length=="") {  
                    alert("Password field is empty");  
                    return false;  
                    }  
                }                             
            }  
        </script>  
</body>
</html> 

auth.php – The PHP code appears to do what’s required here. I’m simply providing it in case you think it requires any changes.

<?php      
    require_once('config.php'); //database details, create connection and check if connection is working or not.
	$username = $_POST['user'];  
    $password = $_POST['pass'];  
        //to prevent from mysqli injection  
        $username = stripcslashes($username);  
        $password = stripcslashes($password);  
        $username = mysqli_real_escape_string($con, $username);  
        $password = mysqli_real_escape_string($con, $password);       
        $sql = "select *from login where username = '$username' and password = '$password'";  
        $result = mysqli_query($con, $sql);  
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);  
        $count = mysqli_num_rows($result);       
        if($count == 1){  
            header('Location: ../record-friday-results.php');  
        }  
        else{  
            header('Location: ../login-failed.php');  
        }     
?>

session.php – If I add require_once(‘…/config.php’); and require_once(‘…/session.php’); files to the top of record-friday-results.php, and I get HTTP ERROR 500

<?php
// Start the session
session_start();
// if the user is already logged in then redirect user to page
    if (!isset($_SESSION['username']) ||(trim ($_SESSION['password']) == '')) {
        header('Location: ../record-friday-results.php');
	else{  
            header('Location: ../login.php');
        exit();
    }
?>

record-friday-results.php

. <?php
//require_once('../config.php'); *commented out so page content displays for you*
//require_once('../session.php'); *commented out so page content displays for you*
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Cue Well Snooker</title>
<link rel="icon" type="image/x-icon" href="/images/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Link css file -->
    <link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
    <div class="header">
        <!-- Logo -->
        <a href="index.php" class="logo"><img src="images/cws.png" style="border: 0px"></a>
</div>
<?php require_once('navbar.php'); ?>
<!-- Container -->
<div class="container">
<div class="pageheading">
<h1>Record Friday Results</h1>
</div>
<div class="formcontainer">
<form method="post" form action="record-friday-results.php">
	<input type="date" id="date" required placeholder="date" name="date"><br>
    <input type="doubles" id="friwinner" required placeholder="Winners" name="friwinner">
    <input type="doubles" id="frirunnerup" required placeholder="Runners Up" name="frirunnerup">
    <input type="doubles" id="frifirstquarter" required placeholder="1st QTR Finalists" name="frifirstquarter">
    <input type="doubles" id="frisecondquarter" required placeholder="2nd QTR Finalists" name="frisecondquarter">	
    <input type="submit" value="Submit" name="insert">
  </form>
 <h3><a href="comp-friday-results.php">View uploaded results</a></h3> 
</div>
</div>
</body>
</html>

Ok, I see the problem.

I’ll explain that HTTP 500 error first. Notice the name of the page you are calling the session.php file from (record-friday-results.php).

Now look in session.php. If the user is logged in, look where they are redirected to (Hint, it’s record-friday-results.php). You are getting a 500 error because the server is getting the files from session.php, and redirects to record-friday-results.php, then gets the files from session.php, and redirects to record-friday-results.php, then gets the files from session.php, and redirects to record-friday-results.php, then gets the files from session.php, and redirects to record-friday-results.php, then gets the files from session.php, and redirects to record-friday-results.php, then gets…

I think you see where the issue is.

The solution would be to add this code at the top of the record-friday-results.php file:

session_start();
// if the user is already logged in then do nothing, otherwise redirect them to the login page. 
    if (!isset($_SESSION['username']) || (trim ($_SESSION['password']) !== '')) {
            header('Location: ../login.php');
        exit();
    }
5 Likes

I tried your solution, but login.php now just loops back after submit
Here’s page code

<?php

session_start();
// if the user is already logged in then do nothing, otherwise redirect them to the login page. 
    if (!isset($_SESSION['username']) || (trim ($_SESSION['password']) !== '')) {
            header('Location: ../login.php');
        exit();
    }
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Cue Well Snooker</title>
<link rel="icon" type="image/x-icon" href="/images/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Link css file -->
    <link href="css/style.css" rel="stylesheet" type="text/css">

</head>

<body>

    <div class="header">
        <!-- Logo -->
        <a href="index.php" class="logo"><img src="images/cws.png" style="border: 0px"></a>
</div>
<?php require_once('navbar.php'); ?>
<!-- Container -->
<div class="container">

<div class="pageheading">
<h1>Record Friday Results</h1>

</div>

<div class="formcontainer">

<form method="post" form action="record-friday-results.php">

	<input type="date" id="date" required placeholder="date" name="date"><br>

    <input type="doubles" id="friwinner" required placeholder="Winners" name="friwinner">

    <input type="doubles" id="frirunnerup" required placeholder="Runners Up" name="frirunnerup">

    <input type="doubles" id="frifirstquarter" required placeholder="1st QTR Finalists" name="frifirstquarter">

    <input type="doubles" id="frisecondquarter" required placeholder="2nd QTR Finalists" name="frisecondquarter">
	
  
    <input type="submit" value="Submit" name="insert">
  </form>
 <h3><a href="comp-friday-results.php">View uploaded results</a></h3> 
</div>
</div>
</body>
</html>

Ok, so then something is wrong here:

if (!isset($_SESSION['username']) || (trim ($_SESSION['password']) !== '')) {

Mess around with this, think through how your system works.

Perhaps this will work:

if (isset($_SESSION['username']) || (trim ($_SESSION['password']) !== '')) {

EDIT: I don’t see in your code where you are defining the $_SESSION variables, that could be the issue.

2 Likes

Mmm! $_SESSION variables. Looks like a new day of reading and learning how to use this. I shall have a go at this tomorrow morning as it’s past my bedtime here.

Thanks for your input. Much appreciated.

You use them the same as any other PHP variable. However, they can be accessed on any page where you declare session_start, and they expire when the browser deletes the session cookie. They are the same as cookies, with the only difference being that the user cannot change them, only the server can.

2 Likes

Hi Greenreader9, I’ve not had any success with various $_SESSION variables codes that I’ve tried. This is leading me to think that the issue is not something to do with session_start, but maybe with the way that my login form is being proccessed. Therefore, if you don’t mind, I’d like to run something by you to see if this triggers something that you might understand better then me : )

The login form has action = “auth.php” and onsubmit = “return validation()”. The auth.php file connect so the db table and checks if username/password are correct. If correct, then record-friday-results.php is opened in my browser. It also is a form that when filled/submitted, send data to another table in my db.
So, could the issue have anything to do with the way that auth.php processes the login.php file or could it have anything to do with the onsubmit = “return validation()”?

If I can’t find a solution, I think I will place any forms where data needs to be sent to my db into a sub folder, and then link the login forms so they only load the sub folder forms after successful login.

You don’t need to do that.

Here is an explanation of how it could be done with your current setup:

After the user submits the info in the login form, check it using the auth.php file. If the information passes, store the username in a session variable. When the user access a page that is restricted, check the session variable against the database. If it matches, do nothing, otherwise redirect them back to the login page.

3 Likes

Thank you for your suggestion. This is exactly what I tried for most of the day yesterday without success. Whatever I try, after form submit, the login form just reloads. So it is looping.
I followed a tutorial found here - How to Use Sessions and Session Variables in PHP (tutsplus.com)

The issue with all these tutorials is that they do not provide comments in the code so that I can edit the code to what I need to have.

For example, what do I edit in this code? Is logged_in_user_id and logged_in_user_name the name of my table row or the id in my login form or what? Where the code shows Tutsplus, what do I put there, my actual password or what? If so, what if you have multiple users with different passwords?

<?php

// start a session

session_start();

// initialize session variables

$_SESSION [ 'logged_in_user_id' ] = '1' ;

$_SESSION [ 'logged_in_user_name' ] = 'Tutsplus' ;

// access session variables

echo $_SESSION [ 'logged_in_user_id' ];

echo $_SESSION [ 'logged_in_user_name' ];

?>

In my auth.php file I added the following -

<?php
// start a session
session_start();
  
// initialize session variables
$_SESSION['user'] = '1';
$_SESSION['pass'] = '*********';
  
// access session variables
echo $_SESSION['user'];
echo $_SESSION['pass'];
?>

I my record-friday-results.php file I added the following

<?php
// start a session
session_start();
  
if($count == 1){  
            header('Location: record-friday-results.php');  
        }  
        else{  
            header('Location: ../login.php');  
        } 
?>

Here, I’ll help you out.

Try this:

auth.php

<?php     
   //Get session information
   session_start(); 
   //database details, create connection and check if connection is working or not.
    require_once('config.php'); 
	$username = $_POST['user'];  
    $password = $_POST['pass'];  
    //to prevent from mysqli injection  
    $username = stripcslashes($username);  
    $password = stripcslashes($password);  
    $username = mysqli_real_escape_string($con, $username);  
    $password = mysqli_real_escape_string($con, $password);       
    $sql = "select * from login where username = '$username' and password = '$password'";  
    $result = mysqli_query($con, $sql);  
    $row = mysqli_fetch_array($result, MYSQLI_ASSOC);  
    $count = mysqli_num_rows($result);       
    if($count == 1){  
        //Initialize session on success
        $_SESSION['user'] = $username;
        header('Location: ../record-friday-results.php');  
    }  
    else{  
        //Clear variable on fail
        $_SESSION['user'] = "";
        header('Location: ../login-failed.php');  
    }     
?>

session.php

<?php
// Start the session
session_start();
// if the user is already logged in then redirect user to page
if (isset($_SESSION['user']) && !empty($_SESSION['user']) {
    //Here, I recommend that you check to make sure the username exists. You don't need to, but it may be a good idea
    header('Location: ../record-friday-results.php');
else{  
    header('Location: ../login.php');
    exit();
}
?>

Replace the first part (before the DOCTYPE) of record-friday-results.php:

<?php
// Start the session
session_start();
// if the user is already logged in then redirect user to page
if (isset($_SESSION['user']) && !empty($_SESSION['user']) {
    //Here, I recommend that you check to make sure the username exists. You don't need to, but it may be a good idea
    //Defining a random variable so PHP does not throw an error. When you check te username agest your database, remove the next line
    $Thisisarandomvariable = "true";
else{  
    //Clear session, just in case
    $_SESSION['user'] = "";
    header('Location: ../login.php');
    exit();
}
?>
2 Likes

[quote=“Greenreader9, post:10, topic:66656”]

<?php
// Start the session
session_start();
// if the user is already logged in then redirect user to page
if (isset($_SESSION['user']) && !empty($_SESSION['user']) {
    //Here, I recommend that you check to make sure the username exists. You don't need to, but it may be a good idea
    //Defining a random variable so PHP does not throw an error. When you check te username agest your database, remove the next line
    $Thisisarandomvariable = "true";
else{  
    //Clear session, just in case
    $_SESSION['user'] = "";
    header('Location: ../login.php');
    exit();
}
?>

[/
Thank you for providing the above. Sorry, but it now has taken me a back to the issue I first had whereby I’m getting a cws.epizy.com can’t currently handle this request.

HTTP ERROR 500

I have to pop out for about 1/2 an hour or so, but will check if you respond when I return. I’ll be available all day should you need me : )

Your resulting page (cws.epizy.com/record-friday-results.php) is returning a 500 error.

Because the session.php file is trying to redirect to cws.epizy.com/record-friday-results.php, I think the 500 error on cws.epizy.com/record-friday-results.php is preventing that from happening.

Because that file is in the root (Which I did not know before), you can’t go back a step, so the correct code would probably be:

<?php
// Start the session
session_start();
// if the user is already logged in then redirect user to page
if (isset($_SESSION['user']) && !empty($_SESSION['user']) {
    //Here, I recommend that you check to make sure the username exists. You don't need to, but it may be a good idea
    //Defining a random variable so PHP does not throw an error. When you check te username agest your database, remove the next line
    $Thisisarandomvariable = "true";
else{  
    //Clear session, just in case
    $_SESSION['user'] = "";
    header('Location: /login.php');
    exit();
}
?>

But you have a login.php file in both the root and the config folder, so I don’t know which one you want to use here. If it’s the latter, you need to remove the ../ from the sesion.php and auth.php files.

2 Likes

Sorry for the confusion of file locations. I’m still getting the 500 error. I tried changing various file path, but continue to get the 500 error.

I tried something, but still get the 500 error.

I saved record-friday-results.php to the config folder, updated all neccessary links/paths in associated files, but still see the 500 error.

Can you share the updated code from the relevent files?

Thanks

2 Likes

I just noticed something I don’t undertsand on the 500 error page.

After submitting the login form I am direct to cws.epizy.com

It makes no difference if I have header(‘Location: /record-friday-results.php’); in auth.php, record-friday-results.php and session.php (all in config folder) or if I have header(‘Location: …/record-friday-results.php’);
The above URL is seen.
Shouldn’t the redirect after submit show the URL as cws.epizy.com if I change the path in all 3 config folder files?

FYI, I tried a different browser (Chrome) and cleared the dns cache.

auth.php

<?php     
   //Get session information
   session_start(); 
   //database details, create connection and check if connection is working or not.
    require_once('config.php'); 
	$username = $_POST['user'];  
    $password = $_POST['pass'];  
    //to prevent from mysqli injection  
    $username = stripcslashes($username);  
    $password = stripcslashes($password);  
    $username = mysqli_real_escape_string($con, $username);  
    $password = mysqli_real_escape_string($con, $password);       
    $sql = "select * from login where username = '$username' and password = '$password'";  
    $result = mysqli_query($con, $sql);  
    $row = mysqli_fetch_array($result, MYSQLI_ASSOC);  
    $count = mysqli_num_rows($result);       
    if($count == 1){  
        //Initialize session on success
        $_SESSION['user'] = $username;
        header('Location: /record-friday-results.php');  
    }  
    else{  
        //Clear variable on fail
        $_SESSION['user'] = "";
        header('Location: ../login-failed.php');  
    }     
?>

record-friday-results.php

<?php
// Start the session
session_start();
// if the user is already logged in then redirect user to page
if (isset($_SESSION['user']) && !empty($_SESSION['user']) {
    //Here, I recommend that you check to make sure the username exists. You don't need to, but it may be a good idea
    //Defining a random variable so PHP does not throw an error. When you check te username agest your database, remove the next line
    $Thisisarandomvariable = "true";
//else{  
    //Clear session, just in case
    //$_SESSION['user'] = "";
    //header('Location: /login.php');
    //exit();
//}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Cue Well Snooker</title>
<link rel="icon" type="image/x-icon" href="/images/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Link css file -->
    <link href="../css/style.css" rel="stylesheet" type="text/css">

</head>

<body>

    <div class="header">
        <!-- Logo -->
        <a href="../index.php" class="logo"><img src="../images/cws.png" style="border: 0px"></a>
</div>
<?php require_once('../navbar.php'); ?>
<!-- Container -->
<div class="container">

<div class="pageheading">
<h1>Record Friday Results</h1>

</div>

<div class="formcontainer">

<form method="post" form action="/record-friday-results.php">

	<input type="date" id="date" required placeholder="date" name="date"><br>

    <input type="doubles" id="friwinner" required placeholder="Winners" name="friwinner">

    <input type="doubles" id="frirunnerup" required placeholder="Runners Up" name="frirunnerup">

    <input type="doubles" id="frifirstquarter" required placeholder="1st QTR Finalists" name="frifirstquarter">

    <input type="doubles" id="frisecondquarter" required placeholder="2nd QTR Finalists" name="frisecondquarter">
	
  
    <input type="submit" value="Submit" name="insert">
  </form>
 <h3><a href="../comp-friday-results.php">View uploaded results</a></h3> 
</div>
</div>
</body>
</html>

session.php

<?php
// Start the session
session_start();
// if the user is already logged in then redirect user to page
if (isset($_SESSION['user']) && !empty($_SESSION['user']) {
    //Here, I recommend that you check to make sure the username exists. You don't need to, but it may be a good idea
    header('Location: /record-friday-results.php');
else{  
    header('Location: ../login-failed.php');
    exit();
}
?>

login.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Cue Well Snooker</title>
<link rel="icon" type="image/x-icon" href="/images/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Link css file -->
    <link href="../css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
    <div class="header">
        <!-- Logo -->
        <a href="/index.php" class="logo"><img src="/images/cws.png" style="border: 0px"></a>
</div>
<?php require_once('../navbar.php'); ?>
<!-- Container -->
<div class="container">
<div class="formcontainer">
<h2>Login Required</h2>
<h3>to record Friday night results</h3> 
        <form name="f1" action = "auth.php" onsubmit = "return validation()" method = "POST">	
		<input type = "text" id ="user" required placeholder="User Id" name  = "user" />
		<input type = "password" id ="pass" required placeholder="*********" name  = "pass" />
		<input type="submit" value="LOGIN" name="insert">
		</form>
</div>
</div>
    <script>  
            function validation()  
            {  
                var id=document.f1.user.value;  
                var ps=document.f1.pass.value;  
                if(id.length=="" && ps.length=="") {  
                    alert("User Name and Password fields are empty");  
                    return false;  
                }  
                else  
                {  
                    if(id.length=="") {  
                        alert("User Name is empty");  
                        return false;  
                    }   
                    if (ps.length=="") {  
                    alert("Password field is empty");  
                    return false;  
                    }  
                }                             
            }  
        </script>  
</body>
</html>

Hi Greenreader9,
Could there be a server issue for sessions?

I have created all new files using codes from here Creating a User Login System with PHP and MySQL - Tutorial Republic

I then created a table name “admin” (updating this in the code in login.php) and tested, but the login form keeps looping after clicking the Login button, which was the exact same problem with my other files.
See - Login (epizy.com)

Username: [email protected]
Password: admin

All the new files are completely different code except for the config.php which only has db connection, which I know works fine as I’ve sent and retrieved data without any issues.

I was just about to give up on this issue when I discovered a solution after reading this article -
Password protecting a directory with a custom login page - Informal - InfinityFree Forum

I downloaded the files from Gethub (link found in the above mentioned article).
I made a few edits and all worked fine, so problem solved.

Thanks for your efforts in trying to help me out here. Much appreciated :smiley:

Yay! My over-a-year-old topic to the rescue. Glad you figured it out

5 Likes