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.
Related
I have php application in that, when user login to application then session started. In session i have stored user type and id. Using user type restrict the access of user pages like add.php, display.php, edit.php etc.
My problem is that the when user login to application that user type and id will be stored in session but when any user change in url like add.php. this page will be accessed by other user.
I want to do when user changes url then say some error message.
<?php
session_start();
if(!isset($_SESSION['username']) || !isset($_SESSION['login_type']) )
{
header("Location:logout.php");
exit;
}
?>
DO NOT just use isset. That will only check whether the variable exists or not and it wont check what value that variable contains
So, you can include something like this in the function
if(!isset($_SESSION['username']) && $_SESSION['login_type'] != 'Admin') )
{
header("Location:logout.php"); //Do not allow him to access.
exit;
}
First of all, when you will be creating a session create session variables that will be having logintype like user,admin,superadmin
And then create a general function to check the session. like
checkSession();
Put this function in a file which you will include it
This function should be able to verify whether the user is authorized or not at the top, before even the file is processed and displayed.
After trawling through other posts, I could not find the answer.
The problem is that when i create a custom session name, I am not able to access session variables on any other pages. How can I get this working with custom session variable?
Scenario A
Login page
after successful login, the following is called
function initiatenewsession($app, $userid){
$session_name = getuniquesessionid($app,$userid); // Set a custom session name
session_name($session_name);
session_start();
session_regenerate_id(true);
$_SESSION["loggeduserid"] = $user_id;
echo("1a)SESSION NAME[".session_name()."]");
echo("1b)logged user[".$_SESSION["loggeduserid"]."]");
}
Echo result
1a) SESSION NAME[myappsessionid6520150528184534]
1b) logged user[65]
Registration page (User clicks a link after logging in)
session_start();
echo("2a)SESSION NAME[".session_name()."]");
echo("2b)logged user[".$_SESSION["loggeduserid"]."]");
2a)SESSION NAME[PHPSESSID]
2b)logged user[]
Scenario B
Login page
after successful login, the following is called
function initiatenewsession($app, $userid){
session_start();
session_regenerate_id(true);
$_SESSION["loggeduserid"] = $user_id;
echo("1a)SESSION NAME[".session_name()."]");
echo("1b)logged user[".$_SESSION["loggeduserid"]."]");
}
Echo result
1a) SESSION NAME[PHPSESSID]
1b) logged user[65]
Registration page (User clicks a link after logging in)
session_start();
echo("2a)SESSION NAME[".session_name()."]");
echo("2b)logged user[".$_SESSION["loggeduserid"]."]");
2a)SESSION NAME[PHPSESSID]
2b)logged user[65]
As per my comment, when you do session_start(), php will check if you set a session name via session_name(), otherwise it'll use its default.
Session startup is basically like this, in php-ish pseudocode:
if (custom_session_name_was_set()) {
$session_name = get_custom_session_name();
} else {
$session_name = ini_get('session.name');
}
if (isset($_COOKIE[$session_name])) {
$id = $_COOKIE[$session_name];
} else {
$id = generate_new_random_id();
setcookie($session_name, $id);
}
$session_data = file_get_contents('/path/to/session/files/' . $id);
$_SESSION = unserialize($session_data);
For your first bit of code, you set a custom name, so that's the name that's used for the session cookie.
In your other code, you do NOT set a custom name, so php uses its default: PHPSESSID. Now you've got two sessions floating around, each with their own unique names, and their own different IDs, and their own separate data in $_SESSION.
If you're going to be using custom session names, you have do session_name($customName) EVERYWHERE you have session_start().
If using a custom session name you must call session_name().
You must call session_start() before headers_sent().
On servers with multiple PHP version support check phpversion() to ensure that the server did not decide to run the wrong version (and hence the wrong session_save_path()).
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']))) {
I have a PHP program, called login.
When the user passes something, like email and password, login.php will return a session key to the user, if the login succeeds.
And I have JavaScript code to call this function to do the login.
How can I store this session key to identify whether the user is logged in?
The session is stored in a cookie by the server.
You don't need to do anything on the client.
a session is serverside.. not clientside.. so you cant set it through js
Sessions are declared manually like this:
$_SESSION['user'] = $_POST['username']; // or any other variable
You can then check on the other pages with PHP like this:
if(isset($_SESSION['user'])){
//do this if true
}
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.