I'm having a problem with a web site I'm creating so I want to know:
How can I prevent that an unauthenticated user could acces the website by doing something like:
Website.com/content
It suppose that unauthenticated user cannot acces the page content, but if they write it directly in the address bar they can see the content. So how can I prevent this to happen? How can make to only allow authenticated users see the content when they write it in the address bar?
I want to do this using cookies... by the way I already implemented the authentication using the database.
place a check
<?
if (!authorized()) { # substitite with your own authorize function
header('401 Unauthorized', 401);
die('You are not authorized!');
}
?>
on the page.
UPDATE: place it before you start output. If you are not using ob_start, that means at the top of your page.
Lets say you have a page for error message "website.com/unauthorize"
and a inlcude file, "check_auth.php", while user logged in, validate user and pass and create a cookie "userLogin" with value 0 or 1.
1 to represent successful login, 0 for invalid id/pass.
and include check_auth.php in every file in which you want restrictions.
include "check_auth.php";
and in this file write:
<?php
if ( ! isset($_COOKIE['userLogin']) && $_COOKIE['userLogin'] != 1 )
{
header("Location: website.com/unauthorize");
}
this will check for login state and will redirect unauthorize users to error page. include this file in all the pages on top where you require restriction.
I'm normally an asp.net developer. And in asp.net we have a master page, It's like a template you can put other content pages into.
If PHP have something similar (include?) Then you could make a function that checks if a user is supposed to be where he is, and if not redirect him to the login page. And include that on all the not-accessible pages.
Related
I have index.php that include pages like
<?php
define('MyConst', TRUE);
include_once('template/header.php');
if (!empty($_GET['action'])) {
$action = $_GET['action'];
$action = basename($action);
include("template/$action.php");
} else {
include("template/main.php");
}
include_once('template/footer.php');
?>
With in a template directory I have main.php which has link to other pages like page1.php, page2.php.
Goto page 1
Goto page 2
How could I prevent users form accessing pages directly typing "http://mydomain.com/?action=page1" on the URL? And redirect them to main.php if they have done it?
You can not. What you want is simply not possible.
For the server side there is no way to know whether an URL is typed or clicked.
If I understand correctly, the thing you want is to prevent the user to access http://example.org/?action=page1 unless they came from http://example.org/?action=main. To do that, you must be able to detect whether they came from http://example.org/?action=main. The safest way to do that is to generate some random value that you associate to the users when they access http://example.org/?action=main and to check whether there is a correct value associated to the users when they want to access http://example.org/?action=page1. If not, they tried to access that page directly.
Check for HTTP_REFERER and if it is not pointing to right values (like your meny page) then redirect user.
Maybe you can try this, On your index.php :
session_start();
if(! isset($_GET['action']))
{
$_SESSION['pageAccess'] = true; # Set the key whatever you want
}
then under that script (we need that session_start() used twice) :
if(isset($_GET['action']))
{
if(! isset($_SESSION['pageAccess']) || ! $_SESSION['pageAccess'])
exit('There is no direct access allowed.');
}
Hope this help, have a nice day.
As per your Question:
There are two approaches that you can follow:
Use HTTP_REFFRER and check on desired page if User is coming from the page u wanted. IF he is accessing the direct URL then show him error page.
Use $_SESSION but this approach can be harmful as SESSION will always be there untill browser / instance closed.
So better to go for 1st approach.
And also as per Pehaa, you can not check id URL is typed
Hey so I have create a login system to a website and I wish to have this login appear when I type in my address. When I have typed in details and logged in, I wish to be redirected to another PHP file, but with the same address.... this way, All I need to do is type in my address if I am allready logged in and I will go to the site which requires login.
I have made a transaction happen identifing if the session is created, if it is, it redirects me to another page, but also to another URL. I tried googleing it, but couldn't find anything exact and straight forward.
Currently:
Login page:
www.example.com
Member page:
www.example.com/members
What I wish for:
Login page:
www.example.com
Member page:
www.example.com
The program structure should look like this.
index.php
if (user is logged in)
display dashoard
else
display login page
Since you are using PHP, make use of session functions. Thus, URL rewriting is no longer necessary.
Update
Assuming if you have file structure in PHP like this:
- index.php
- login.php
+ template
- login.php
- dashboard.php
You can do the following structure in index.php file.
define('IN_FILE', true);
if (isset($_SESSION['user'])) {
require 'template/dashboard.php';
} else {
require 'template/login.php';
}
In template/dashboard.php
if (!defined('IN_FILE')) {
exit;
}
// Then your HTML, PHP and whatnot
And in login.php
if (!isset($_SESSION['user'])) {
require 'template/login.php';
} else {
header('Location: index.php');
}
Change the code according to your needs.
This can be achieved using several approaches.
a) Use session to determine the current page, so if a user click on a link, create a session store the value and on page load read the session data and include the file accordingly.
b) Use URL parameter to determine the page (this is the most common approach). for example in index.php you can add more parameters like index.php?page=somepage and by reading the value using $_GET and including the PHP file accordingly.
There are some more way to achieve what you want to, for instance using javascript/jQuery this is possible.
So I've got a Backbone application + web homepage. Right now, if you login to my website, I create a global object with your user details from the database. However, you can still just hit one of the routes in the application directly.
How should I handle users who are not "logged in" and redirect them to a "you must login page"?
Is this a standard operation? Basically, I have a REST url setup that returns just
{ sessionId: [php-session-id-here] }
If they are logged in, it would return something more like this:
{
sessionId: [php-sess-id],
userId: [user-id-from-db],
firstName: [f-name],
lastName: [l-name]
}
Ideas? Thanks!
What I've done in the past is to include on every page along with jQuery (actually, added to the jQuery file) an extension on the AJAX method to check for a custom code that I send when a user isn't logged in. When that value was seen it redirected the user to the login page regardless of what was going down.
This was because that site had a time out on login, so a user could get logged out while sitting on a page and then the AJAX request would just fail. If you don't have a timeout on the login the odds of ever seeing this issue are slim. Just ignore requests that come from users that aren't logged in.
If you need help coding this, start here: Extending Ajax: Prefilters, Converters, and Transports.
Really shouldn't require anything as complex as pseudo-code:
JS needs to do some AJAX, so JS talks to server
PHP checks for login if needed
If not logged in, send back the abort message (I used a converter to catch a "notLoggedIn" dataType. However this could also be done with a transport, they are just more complex.)
JS sees the abort message and does a window.location redirect rather than return AJAX message.
If you want, you could load a lightbox with a login form and send that via AJAX to PHP where a re-login can take place, if you remember the AJAX attempt that failed you can send it again after login. Then the user doesn't even need to leave the page to log back in.
If you're using jQuery, you can set a global ajaxSetting that allows you to do certain things upon certain http codes. Some pages I read recommend adding to your JSON a url field to point to where to login, but I figure that's just up to you. So the only modifications you'd need to implement what I've mentioned is 1. change the http code to something reasonable like 401 (unauthorized) and implement the http code handler. But I wouldn't call this standard, I'd just say that's what several people have done (including myself).
<?php
function IsLoggedIn()
{
if(isset($_SESSION['id'])) // Change that to what you want
{
return 1;
}
else
{
return 0;
}
}
?>
Then in your code, you could use something like:
if(isLogged()){ header('Location: http://google.com'); }
I want the following:
After logging in, A user will have assigned session variable, and the logging in page will be refreshed. The URL should not be changed at all but the page would be different.
I don't know the idea of doing that.
I know that Facebook does it. (Logging in, and logged in page url is same but different page)
I'm using nginx, PHP.
Should I some sort of rewrite URL? or some configuration on nginx? Or should I manipulate header with php in some way? then how to?
just do a conditional on an include. In general if the session does not exist you say something like
<?
if (!isset($_SESSION['user'])){ include_once("login_please.php"); exit(); }
..actual page content
?>
Use PHP to decide what to show (or which page to include) based on the session variable.
if ($_SESSION['form_submitted'] == true) {
include('content.php');
}
else include('form.php');
I have a web app where most of the functionality is within a javascript file, and I am about to introduce a pro version of the app in which registered users would get access to more functionality.
Again the extra functionalities are just extra functions in a javascript file.
What I am planning to do is:
- link pro_script.js if user is logged in,
- or link to normal_script.js if user is not logged in,
at the header of the page via user authentication with php.
I was wondering if this is the best way to approach this situation?
I have concerns that the pro_script.js is residing accessible under the javascripts folder, and it would be possible to write a script or plugin that loads the pro_script.js instead of normal_script.js.
You can have your HTML to call my_script.php instead of my_script.js. This PHP file would simply output your JS depending on the state if the user is logged on or not.
You can hide pro_script.js behind PHP script - it will check user's account and if user is "premium" then it outputs content of pro_script.js, otherwise - empty string. Don't forget to setup correct headers (content-type and caching)
This is acually #Adnan's idea, but my response was far to complex for a comment.
Your my_script.php should look something like this:
<?php
session_start();
header("Content-type: application/x-javascript";);
if (!empty($_SESSION['PRO_USER'])) {
echo file_get_contents("js/pro_script.js");
} else {
echo file_get_contents("js/normal_script.js");
}
exit;
?>