Redirect to login with dynamic URL (?p=) doesn't work
I have two webpages that I want to be accessible only when the user is logged in. One for admin and one for other users. When a user who isn't logged in arrive to these pages I want to redirect the page to login.php. This doesn't work with the website I am working on.
I use this script on the startpage:
<?php
if(file_exists($_GET['p'].".php")){
include($_GET['p'].".php");
}
else{
if(empty($_GET['p']) OR $_GET['p'] == ""){
include("main.php");
}
else{
include("404.php");
}
}
?>
and therefore my links have this format: ?p=mapp/filnamn and it doesn't work with header('Location: /?p=admin/login');
If I skip this script and use ordinary links header('Location: /admin/login.php'); it works, but I don't want to be forced to copy the same code over and over again to get header, footer, leftbar and rightbar on every single page.
I have almost teared my brain apart to find a solution but in vain. Today I have been sitting in front of the computer almost the whole day with this problem, but no luck. I don't even know what to search for. What is it I don't understand? Not long time ago I hade another problem just because I use dynamic links.
This is the script I use on the page that I don't want to be accessible if you aren't logged in:
<?php
session_start();
$username = $_SESSION['username'];
include ('functions.php');
db_connect();
if(!empty($_SESSION['username'])){
$sql = mysql_query("SELECT username, usertype FROM users WHERE username='$username'");
$result = mysql_num_rows($sql);
$row = mysql_fetch_array($sql);
if($_SESSION['username'] = $username AND $row['usertype']==1){
$_SESSION['username'] = $username;
$user_welcome = "Welcome ".$username;
}
else{
//header('Location: /?p=admin/login');
die("<a href='?p=admin/login'>You have to login as admin to access this page!</a>");
}
}
else{
//header('Location: /?p=admin/login');
die("<a href='?p=admin/login'>You have to login to access this page</a>");
}
?>
I use "die" because it is the only way for me to make it work, but I want to use what is in the comments. Maybe it's not such a bad idea to use the method I use today, but the problem is that when I get the message that I have to login to view the page, the rightbar disappear and the page therefor looks stupid.
Another question I am wondering about, is if the above script is secure? It doesn't feel like it, but maybe the security is all about the loginpage?