i have an issue, my code works wonderfully for the pupose its designed for however for security reasons i need th epages page my login page to have either randomized links or just links that cannot be bookmakred too so that one can bypass the login page. My login page is set up to do a basic query from a table of usernames and passwords and so far thats been great but like i said before i need the page to be random each time. How do i go about doing this? I know only what i have read so far online and thats very little about this subject. Here is my code so far:

<?php

session_start();
$con = mysqli_connect("localhost", "root", "", "numbers") or die(mysqli_error($con));
if(isset($_POST['login'])){

$myusername=mysqli_real_escape_string($con,$_POST['username']);
$mypassword=mysqli_real_escape_string($con,$_POST['password']);

$sql="SELECT username, password FROM admin WHERE username='".$myusername."' AND password='".$mypassword."'";
$check= mysqli_query($con,$sql);
$row = mysqli_fetch_row($check);
if($row[0]!="" && $row[1] !=""){

 ## set logged_in to true
$_SESSION['logged_in']= true;
 ## set username session
$_SESSION['username'] = $row[0]; 

header('location: form.php');
exit();
}
else
{
$error="Your Login Name or Password is invalid";
//echo "$error";
//echo "<META http-equiv=' refresh' ;URL='index.php'>";
}
}
?>
<html>
<head>
<!-- Basics -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Login</title>
<!-- CSS -->
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<!-- Main HTML -->
<!-- Begin Page Content -->
<div id="container">
<?php echo ($error ? $error : '' );?>

<form action="index.php" method="post">

<label for="name">Username:</label>
<input type="name" name="username" id="username">
<label for="username">Password:</label>
<p><a href="#">Forgot your password?</a>
<input type="password" name="password" id="password">
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
<input type="submit" value="Login" name="login" id="login">
</div>
</form>
</div>
</body>

</html>

thats the login portion if anything else is needed please let me know. thanks for the assistence

Member Avatar for Zagga

Hi,

I think standard practice would simply be to check for your $_SESSION['logged-in'] variable on each restricted page ...

session_start();
if (!isset($_SESSION['logged-in']) || $_SESSION['logged-in'] == false){
    header('location: login.php');
    exit();
}

Is there any particular reason you need randomised links?

To add Zagga's remarks, when a user accesses any page on your site that requires the user to be first authenticated, you simply need to check for something before you show the user the content of the page. As Zagga indicated, its common to store some information in a session variable because you can easily check the value of a sesssion variable. if you do not find the expected logged in data, you rediret the user to the login page. ASide from a session variable, you can store this information in a cookie, especially if you want to set up some type of persistent logged on status, or you can store the info in a database table (probably least approach used).

to answer zaggas comment i need randomized links because i can get on the page past the login prompt without needing to login because i can bookmark the link, i may have my login page set up incorrectly but im not at all sure how to do that if i do. I am somewhat understanding that i need to set each login up with a session and then direct it to the appropriate page via header, will this hide the link so that a user cannot pass through without entering the correct login information, my program will run via local server and be accessible to only people on that network if that makes any difference, sorry but this is all very new to me so if i sound like im ignorant or lost i apologize.

also thank you zagga for the example code, i very much appreciate that, helps me understand a little easier when i can see what i have to do :D

Member Avatar for Zagga

Hi again berserk,

Sorry for my brief first answer, I'll try to explain the idea.

In your original code, you set a session cookie after the user has successfully logged in (line 16) then the user is redirected to form.php

If you place the code I supplied at the top of form.php (and every 'member only' page) it will check to see if $_SESSION['logged-in'] has been set. If it has been set, the rest of the page is run. If it hasn't been set, the user is redirected to login.php.

Even if a user has bookmarked form.php, when they visit it, the code checks to see if $_SESSION['logged-in'] has been set. So if they haven't come via the login page (session variable NOT set) they will be redirected to login.php.

Session cookies are deleted when a user closes their browser.

Example run through 1.
1) User A visits your site and uses their username and password to login.
2) User A is redirected to your restricted form.php page successfully because the session variable was set during login.
3) User A bookmarks form.php and closes their browser.
4) User A opens their browser and opens the form.php bookmark.
5) User A is redirected to login.php and has to login again because their session variable was deleted when they closed their browser.

Example run through 2.
1) User B browses directly to form.php without logging in.
2) User B is rediected to login.php because there is no session variable set.

This should avoid the need to use randomised links.

commented: good explanation. +12

okay now im getting this error in my code

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\AppServ\www\Multi_Delete\header.php:12) in C:\AppServ\www\Multi_Delete\form.php on line 5

Warning: Cannot modify header information - headers already sent by (output started at C:\AppServ\www\Multi_Delete\header.php:12) in C:\AppServ\www\Multi_Delete\form.php on line 7

I added the code at the top of my form page like you explained and i inspected the rest of my code and from what i see it should be working but its not, help please lol.

here is the form code:

<?php 
include('header.php'); 
//include('index.php');

session_start();
if (!isset($_SESSION['logged-in']) || $_SESSION['logged-in'] == false){
    header('location: login.php');
    exit();
}

?>
<body>

    <div class="row-fluid">
        <div class="span12">




            <div class="container">
            ......
            ......
            ......
            rest of code.....

this is what the top of my page looks like do i have to also put this check in the login page? and why would it tell me i cannot modify the header?

Member Avatar for Zagga

Hi beserk,

session_start needs to be placed directly after you start PHP, before you output anything to the browser (including blank lines). The error message is showing that header.php is causing the error at line 12 (of header.php) and I assume this is where you output (echo) something. index.php may also have some form of output so you need to open the session BEFORE all of this. The first 8 lines should be rearranged slightly...

<?php
session_start();
if (!isset($_SESSION['logged-in']) || $_SESSION['logged-in'] == false){
    header('location: login.php');
    exit();
}
include('header.php');
//include('index.php');

You need to open the session on any page that either sets or uses $_SESSION variabes, so you will need to open the session in login.php so you can set $_SESSION['logged-in'] (again, place session_start(); at the very top of the page) but you do NOT need the check to see if the user is logged in, this only needs to be on restricted/member-only pages.

You can read all the details about sessions here and you can read about session_start specifically, here.

I hope this helps but let us know if you need any more info.
Zagga

ok im definitly getting somewhere but i cant seem to wrap my mind around this one. I fixed it and now im not getting any errors back BUT when i login it just returns me to the login page and doesnt actually direct me to the form page im trying to get to, then i changed the login.php to form.php and im getting an infinite loop which i didnt think was gonna work but i was just testing. do i have to change something in the index/login.php or do i have something else wrong? I apologize for being such a hassle i just keep taking steps and running into errors but im definitly making progress cause when i typ emy login information in i dont get an invalid prompt and when i try to access the form page it takes me to the login page which is what i want but now i just need to fix this recent issue.

Member Avatar for Zagga

Have you still got $_SESSION['logged_in']= true; in your login page, just before the redirect to the restricted page (line 16 of your original code)?

Member Avatar for Zagga

To clarify ...

login.php (slightly changed to improve security)

<?php
session_start();
$con = mysqli_connect("localhost", "root", "", "numbers") or die(mysqli_error($con));
if(isset($_POST['login'])){
    $myusername=mysqli_real_escape_string($con, filter_var($_POST['username'], FILTER_SANITIZE_SPECIAL_CHARS));
    $mypassword=mysqli_real_escape_string($con, filter_var($_POST['password'], FILTER_SANITIZE_SPECIAL_CHARS));
    $sql="SELECT username FROM admin WHERE username='".$myusername."' AND password='".$mypassword."'";
    $check= mysqli_query($con,$sql);
    $row = mysqli_fetch_row($check);
    if (mysqli_num_rows($row) == 1){
## set logged_in to true
        $_SESSION['logged_in']= true;
## set username session
        $_SESSION['username'] = $row[0];
        header('location: form.php');
        exit();
    } else {
        $error="Your Login Name or Password is invalid";
    }
}

// Rest of your login page here (the HTML).
?>

form.php

<?php
session_start();
if (!isset($_SESSION['logged-in']) || $_SESSION['logged-in'] == false){
    header('location: login.php');
    exit();
}

// Rest of restricted page here.
?>

yes i still have it and it gives me that error still, and also the changes u made for the form page i had originally and they didnt work, or at least the logic part of testing the row[] was wrong for me and i had to change it to what i have up there so im still stuck :/

Member Avatar for Zagga

Hi beserk,

I just spotted my typo that is probably causing the problem, my bad.

In login.php you set the variable $_SESSION['logged_in'] (using an underscore) but the code I gave you for form.php checks for $_SESSION['logged-in'] (using a hyphen). Make these both the same and you should be good.

PERFECT! this is EXACTLY what i wanted, gotta love them tiny typos, you sir are a true friend now i can add some more to my program and hopefully have it up and running within the week, tysm!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.