PHP How to display page based on session? - php

I am making a website. Most of it is available to anybody visiting the site, but a small portion of it requires you to register to view. I have set up the login with Sessions. After someone logs in, it sets this:
$_SESSION['login'] = TRUE;
In one of the exclusive pages, at the top of the code before the content, I have written
if ($_SESSION['login'] == FALSE) {
header("loginpage.php");
}
However, if somebody is not logged in, that variable does not exist, and I end up with an error. Is there any other way to check if somebody is logged in? I would like something similar to what I already have, because I don't want to have to change everything.

You can use isset function to determine if a variable is set and is not null.
if (!isset($_SESSION['login']) || $_SESSION['login'] == FALSE) {
//user isn't logged in
header("loginpage.php");
}else{
//user is logged
}
Check the manual.

if(!#$_SESSION['login'])
{
header("location: logingpage.php");
exit();
}

Simple solution : in the first page (or first script) of your website, create the session variable with value "false" :
<?php
session_start();
$_SESSION['login'] = FALSE;
?>
And, after some successfully logins you change the value to TRUE (as you are already doing) :
$_SESSION['login'] = TRUE;
This way the session variable will always exist, and you will not have problems with "unset" variables.

Do you have a script that always runs before each page executes? If not, this is a great place to set up any utility functions or initialize variables, like $_SESSION['login']. You can set a default false value for $_SESSION['login'] there. Then you have a reliable default value, which is a good practice for a variable that's important, like this one.
You could use this to check if it's set and assign a default:
//Right after starting the session
if (!isset($_SESSION['login'])) {
$_SESSION['login'] = false;
}
If it's already got a value, this will be skipped.
You can also add an # before a variable when you want to use it but you can't be sure it exists. This will suppress warnings about the existence of the variable, but I think it's better to know what the default value should be. Sometimes it's useful to get those warnings.

Related

session variable sets on one page and find empty on another page

Hello Friends I am new at forum
I have create a simple login page name as index.php with following code:
// I have already starts session by session_start()
$qry="select empCode from relaxo_employee_info where empCode='".$username."' and empPassword='".$password."' and empPost='Executive'";
$result=mysql_query($qry);
if($row=mysql_fetch_array($result))
{
$_SESSION['UID']=$username;
echo $_SESSION['UID']; //prints session data successfully so think session set correctly.
?>
<script>self.location.href='executive/order_place.php';</script>
<?php
}
then at starting of order_place.php I continue the session by session_start() and the following code in it to check valid session
<?php
session_start();
if(isset($_SESSION['UID'])==NULL) // at this point $_SESSION['UID'] find automatically empty. somehow Its blank completely.
{
?>
<script>self.location.href='index.php';</script> //because of session finds empty it redirects to index.php
<?php
}
?>
and strange things are happens I just share with u which helps you understand my problem
1) the same code is run on localhost successfully and does not work on my domain
2) sometimes session works successfully but sometimes not with same code without any changes
So guys please solve my problem and help me to come out from this issue
if(isset($_SESSION['UID'])==NULL)
is kind of a weird approach if you want to compare the $_SESSION variable with NULL. Instead, try
if(is_null($_SESSION['UID']))
and see if the problem still occurs.
Try like this...
<?php
session_start();
if(isset($_SESSION['UID'])) // check whether session is set or not.
{
if($_SESSION['UID'] == NULL) // check session is NULL
{
header('location:index.php'); // redirect to index.php page
}
}
?>
if(isset($_SESSION['UID'])==NULL) is where your problem is. If true == null or false == null it's never going to work.
isset($_SESSION['UID']) tests to see if your variable is set.
in order for you to test it's value try something:
if( isset($_SESSION['UID']) && trim($_SESSION['UID'])!='' )
{
// execute code here
}

validation user using $_SESSION in PHP

I have a php page that should only be accessed by admin. I am using a php $_SESSION to validate the user. I have this code segment on top of my page which should only be accessed by the admin
if (!isset($_SESSION["uname"])) {
header("Location:../error.html");
exit;
}
if ($_SESSION["uname"] != "admin") {
header("Location:../error.html");
exit;
}
uname variable is getting pass to the page correctly, I am sure about that. But my validating process does not work as I expected. any user can access the page.
Is there anything wrong I have done here.
Did you output anything before doing these checks, even a single empty line is enough to prevent redirecting the page using
hearder()
As others stated I'd make sure you do
session_start();
But I have to assume you have the correct session values as you put
"uname variable is getting pass to the page correctly, I am sure about
that. But my validating process does not work as I expected. any user
can access the page. Is there anything wrong I have done here."
So that leads me to the header error, one way to tell is adding.
ini_set('display_errors', 1);
above your "validation checks" this should show any errors like "unable to send headers output already sent" etc.
Did you call session_start() function at beginning.
It would not work unless we call session_start before using any SESSION data.
http://www.php.net/manual/en/function.session-start.php
You probably forgot to call session_start() at the very beginning of the restricted page as well as the page where $_SESSION['uname'] is being set. Also make sure that $_SESSION['uname'] does not contains the value of 'admin' for other logged in users.
Note: You can debug values of super globals like $_SESSION using the print_r() or var_dump() functions.
See the example given below;
Start your session in your index or the desire page
sesstion_start();
Create this function to validate and redirect automatically
function isValidate($value, $autoRedirect = true){
if(empty($_SESSION['uname']) || $_SESSION['uname'] != $value){
if($autoRedirect){
header("Location:../error.html");
exit;
}else {
return false;
}
}
else {
return true;
}
}
Now simply call this method to validate the session by name. For example;
isValidate("admin");
isValidate("user");

session not working the way it should

I am using sessions to keep track of users.
on another page it sets the username and password variable when the user logs in and then redirects to this page.
for security reasons when the user comes here I want to check that the user is logged in. If the user isn't logged in then it will redirect the user to the index.php page
<?php
session_start();
if(isset($_SESSION['sessionid'])) {
if (isset ($_SESSION['username' and 'password'])){
}
else
{
header("Location:Index.php");
}
}
?>
the problem is that if I just load the page by typing in the relevant URL I am not redirected to the index page
Any help is appreciated
I would highly recommend against storing that information in the session. That being said, you have an error in your syntax:
if (isset ($_SESSION['username']) && isset ($_SESSION['password'])) {...}
But, if I can add further, I would recommend (at very minimum) creating either a class or function to do this for you, as you'll be using it more than just once I assume.
Create yourself a function, for example:
function is_logged_in () {
if ((isset ($_SESSION['username'])) && (isset ($_SESSION['password']))) {
/* this is an awful way of checking if a user is logged in! */
return true;
} else {
return false;
}
}
Then, when you need to check if a user is logged in, just reference that function:
if (is_logged_in ()) {
/* show members only stuff */
} else {
echo 'Please login';
}
Then, as you learn more and proceed with your application you can adjust one function instead of having to go back and update the login check everywhere in your code.
BUT: Please, please, please read up on user security, or even better use one of many pre-made packages.
Cheers.
This is wrong way of checking in if statement use this
if (isset($_SESSION['username']) && isset($_SESSION[ 'password']))
With isset ($_SESSION['username' and 'password']) you don’t check whether the two variable $_SESSION['username'] and $_SESSION['password'] exist but whether the $_SESSION variable with key 'username' and 'password' (which evaluates to true) exists, so basically isset($_SESSION[true]).
You actually need to list both variables:
isset($_SESSION['username'], $_SESSION['password'])
You have a sintax error in your if condition, you need to declare your session values separatly so change to this
if((isset($_SESSION['username'])) && (isset($_SESSION['password']))) {

Check if session is set or not, and if not create one?

I want to check if a session is currently set, and if so do allow the page to run as normal (do nothing) if not create a session.
I had a look at another SO question, in which the following code was posted:
if ( empty( $_SESSION['login'] )) { } else { }
Would the easiest way to do this be to set something like $_SESSION['a'] for each session, and then run if(empty($_SESSION['a'])) to check if a session exists?
Then again, can you use a session variable without invoking session_start() in the first place, thus making it obsolete (I tried this yesterday, as an echo though, not an if statement to check that a variable was carrying through without realizing that session_start() needed to be invoked before I could echo the variable).
There's probably an easy way that's oft used, I just can't seem to find it.
Any help would be greatly appreciated!
session_id() returns the string identifying the current session. If a session hasn't been initialized, it will return an empty string.
if(session_id())
{
// session has been started
}
else
{
// session has NOT been started
session_start();
}

preventing direct access to a php page, only access if redirected

I want to make my php page only accessible from another page redirect and prevent my user from accessing it directly.
I mean, let's say I have a page called "main.php" and another PHP file that I want to prevent direct access to, called "noaccess.php".
I want to make noaccess.php accessible only if I redirect from main.php
Any suggestions?
UPDATE: Session is a good idea, but the problem is I have to use JavaScript to redirect the page, so the question is, can I use ajax to set a PHP session?
UPDATE 2: OK I found the solution, I don't need preventing direct access now, as I can check from mysql whether the page needs to be accessible or not.
What if everytime you were going to redirect you saved a value in the $_SESSION variable. So you have
//code
$_SESSION['fromMain'] = "true";
header("Location: noaccess.php");
Then in noaccess.php put
if($_SESSION['fromMain'] == "false"){
//send them back
header("Location: foo.php");
}
else{
//reset the variable
$_SESSION['fromMain'] = "false";
}
I really don't know if this would work or not, but this is what I would try off the top of my head.
try this
if (!isset($_SERVER['HTTP_REFERER'])){
echo "uh?"; }
else {
// The script
}
I think you're probably coming at the problem from the wrong direction, but if you really want to implement this I'd most likely do it with a session variable. Just have main.php set a flag indicating that they're now able to access noaccess.php and then redirect there. noaccess.php checks for the flag, and only functions if it's been set.
To prevent access to pages, the best practice is to use session variables say $_SESSION['username'] and $_SESSION['password'] to check against your database table record assuming your table name is "users", the fields 'username' and 'password' in order for users to gain access to the page, else they are redirected to the log in page for them to supply the correct username and password through the input field.
Below is an anatomy of Preventing Direct Access to a PHP Page.
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$query="select * from users where username='$_SESSION[username]' and password='$_SESSION[password]'";
$result=mysql_query($query);
if($result)
{
echo "Your login was successful..";// the page you want to go to if login successful
{
else
{
header("Location:index.php?action=login");//any page you want to return to if log in failed
}
I know this has already been answered. Although the answers are good, I was just facing the same situation so I thought I would put my two bit in.
I would not use HTTP_REFERER It is not reliable and not every browser even shows it.
I would not use a session variable as that is stateful and you will have to write more lines of code to check it on every request leading to unnecessary bloat.
Ideally I would create a controller class with two functions main and no access
Or If you dont want to go through that trouble, I would create a variable which is globally accessible in noccess.php with a simple true false.
This is what I would do:
class Access{
protected $access = false;
public function main(){
//Authenticate and set
include_once 'main.php';
$this->access = true;
}
public function no access(){
if($this->access === true){
include_once 'no access'.php;
}else{
header('location: main.php');
}
}
}
Or if you dont want to go through that trouble You could create a simple function or set a simple variable which is accessible from noaccess.php:
//main.php
$access = false;
header('location: noaccess.php');
//noaccess.php
include 'main.php';
if($access){
//Continue
}else{
header('location: main.php');
}
Im sure you could simplify this, but this would be the simplest and safest approach rather than relying on server variables.
I would not use a $_SESSION or $_POST as that means unnecessarily posting a form when all you want to do is secure access
You can use $_SERVER["HTTP_REFERER"]. Put the following code in the beginning of your php file and set $url to be equal of your desired url for example http://a.com/main.php
if ($_SERVER['HTTP_REFERER'] != $url) {
header('Location: noaccess.php');
exit();
}
Why not to just include instead of redirect?
The other folks are right there are issues with $_SERVER["HTTP_REFERER"] so I guess the best way will be to have a variable set into a $_SESSION or $_POST and you will need to check if that variable exists, if not it means it is a direct access.
You tried on this Iva. Below is the code that works:
$url != 'your-url-which-you-do-not-what-direct access';
if ($_SERVER['HTTP_REFERER'] == $url) {
header('Location: otherurl.php'); //redirect to some other page
exit();
}
Ensure this appears at the top of the page where you do not want direct access to.
I think I am late to answer this but my way would be
<?php
$page = basename($_SERVER['PHP_SELF']);//gets current URL
if ($page == "nonaccesspage.php") //any page u don't want to be accessed directly
header('Location:index.php');
else if($page == "nonaccesspage2.php") //page 2 which is not accessible
header('Location:index.php');
?>
If you want to authorize the user for accessing the page (I mean there is a page which is not included but can be accessed with the URL) just use $_POST or $SESSION for authorizing the user with ID and password or something like that.

Categories