session not working the way it should - php

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']))) {

Related

PHP How to display page based on session?

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.

Using isset php function to determine is a key is set in the super global Session array

I have a page called login.php. Login.php processes user information. If the passed user information is found in the database a new session is started. The name and password are then added to the super global sessions array
if(correct_password($name, $password, $users, $users_size)) {
session_start();
$_SESSION["name"] = $name;
$_SESSION["password"] = $password;
header("Location: account.php");
After the validation the user is redirected to account.php. I want to ensure that the user is logged in i.e the "name" index is set before they can access account.php. In order to do this I have the following code
if(!isset($_SESSION["name"])) {
header("Location: index.php");
die;
}
This code is suppose to check to see if the "name" index is set. If it is not set it means the user is not logged in and should therefore be directed back to index.php. However it seems that even if the user logs in the if always is true. I even tested
echo isset($_SESSION["name"]);
die;
to simplify things. When this is done nothing appears on the screen meaning that isset evaluated to false. If I try to print the global sessions array in account.php it works. The data prints and it shows that the name field is populated with the data submited from login.php.
What am I misunderstanding about isset? Or did I mess up somewhere else.
Thanks in advance.
You also need to have session_start(); on top of the page where you check for that value, not only where you set it.
session_start();
if(!isset($_SESSION["name"])) {
header("Location: index.php");
die;
}
This can also work for you:
if( false == isset( $_SESSION ) && false == isset( $_SESSION['name'] )
header("Location: index.php");
die;
}
Storing username and password either in cookie and session is not a good idea
try this will help you out
if (isset($_SESSION['name']) && null != $_SESSION['name']){
//name is exist don't forgot validate username against database
}
Hey to everyone who answered this question thank you. All your answers worked. The reason I thought they were not working is because I forgot to destroy the session after the user logged in. So even after log out the name index was still set.

session protection

I am creating a webpage bit by bit, testing parts of the webpage ideas. I want to learn how to session protect a page. I have already password protected a page seccsesfully, but anybody can access the page by typing in the url. i want to session protect my page so no one can do that. i have three pages: index.html, which has the form which sends the the password.php, the password.php, which makes sure that the password and username are correct using "if statments"(here is the "if statment")
if ($username == 'mgmb99'){
if ($password == 'mgmb91mas'){
header('Location: youhere.php');
} else {
echo 'your username or password is wrong. go back to login page ';
}} else {
echo 'your username or password is wrong. go back to login page ';
};
, and the youhere.php which is the page once you logged in.
$_SESSION['connect']=0;
Sets the connect value in session to be 0.
Currently this check:
if((!$_SESSION['connect']))
Will always return true because if $_SESSION['connect'] is unset then !$_SESSION['connect'] will be true. Likewise if(!0) will be true.
Try setting $_SESSION['connect'] to true or 1 or the like or, alternatively, change the check to be:
if(!array_key_exists('connect',$_SESSION))
( ! $_SESSION['connect'] ) will is true when the session variable isn't set but also when it is set to 0. So if you want to protect youhere.php, you need to assign another value and check for it.
Also session_destroy() will delete all session variables, so you login, you go to youhere.php but if you refresh the site, you will instantly be logged out
There is a plethora of information on Sessions on the PHP website.
http://www.php.net/manual/en/intro.session.php
Here's an example with storing and killing session variables.
http://www.php.net/manual/en/session.examples.basic.php
To set a Session var:
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
To kill the session var:
<?php
session_start();
unset($_SESSION['count']);
?>

php remembering a session

Im trying to stop users of my spacebook page from navigating to other pages without having logged in first. I understand I am supposed to use session variables. I know I have the user remembered on a specific session by entering session_start(); at the top of the page. Would a new class file be necessary have the browser remember the client is logged in or not? Would the session need to be stored stored in the class object? If a user navigated to a page where access was authorised before they could get there where would I store the if/else statement needed in a seperate php file?
If a new class was necessary Im thinking it would look something like this:
class Loggedin {
private $isLoggedIn;
public function Loggedin($username) {
if (array_key_exists($username, $this->isLoggedIn) && ($this->isLoggedIn[$username] == $password))
{
return true;
}
else
{
return false;
}
}
}
After the User has been logged in you can simply store the User ID in the $_SESSION variable like this:
login.php:
if (login_correct($userid, $password)) {
// Login successful
$_SESSION['user_id'] = $userid;
}
An other PHP-file could look like this:
if (null !== $_SESSION['user_id']) {
// User ist logged in...
} else {
// User is not logged in!
}
Your logout.php can look like this:
$_SESSION['user_id] = null;
I think you are way over-thinking this.
Passwords never get stored for longer than they are needed (i.e. the initial authorization request, so your $password is not necessary, not that it's defined anyway).
You have access to $_SESSION everywhere. It's up to you if you want to wrap it in a class.
The authentication check is as simple as isset($_SESSION['username']) (assuming you set that session value on login.
The $_SESSION variable in PHP is something they called a superglobal. This means that this variable is accessible from any scope throughout your application. Simply use $_SESSION.
Same goes with $_GET, $_POST, $_REQUEST, $_SERVER and $_ENV. I'm sure I'm missing one somewhere :D
Remembering a user can be as simple as (after login success):
$_SESSION['userid'] = 1234;
Another page would query it like so:
if (isset($_SESSION['userid'])) {
// user is logged in
}
There's no need to store an object in the session to accomplish this.

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