I am working on a the backend of a website. It is already working, and everything is in place, but I recently built a user management section. Now I would like to create user rights for users, and only allow those who are set as administrators on the database to access the user management pages.
I had done something with .NET which has a very nice authentication feature, and on page load I check if the user is authorised to access this page, if not redirect him to an access denied page. Is there something similar for PHP? Which would get the username of the user logged in and check it with the database, if he is allowed he would see the website, otherwise he gets redirected to an access denied page.
If there is a better solution, please feel free to post it here!
It really depends on what you need the system to handle. Most PHP-based authenication systems use session variables and MySql to store and keep active user information available to the application. I've never used this, but SUMO is apparently an easy to implement authentication system. It's also relatively easy to build a basic user authentication/permissions system with PHP. A google search will bring up thousands of tutorials.
Here is a basic(for-starter) example:
In every page(place this a the top: line:1) that requires authentication:
<?php
session_start();
//check if login key is already present, if yes user is already login
if(!isset($_SESSION['login']) {
header('location: login.php'); //redirect to login page
}
//sample of accessing a session variable
echo "current user is ", $_SESSION['username'];
?>
On login page:
<?php
session_start();
//check if user credentials
if(username and password) {
//set a marker on the session
$_SESSION['login'] = true;
$_SESSION['username'] = $username;
//place additional info on the session
}
?>
On you logout page:
<?php
session_start();
unset($_SESSION['login']);
//or $_SESSION = array(); //clears all session variables
?>
Related
I used Guzzle lib for my project.
I use guzzle to log in to a website (domain.com/login.php) and then I can get another (domain.com/post.php) as a logged in user.
The question is "How I can use cookies to load (domain.com/post.php) many requests as I want without log in the website again?"
My mine is something like that:
login = check cookies saved
if ( login ) then get domain.com/post.php
else
log in again, then get domain.com/post.php
Many thanks.
Simply Like,
PHP Sessions
PHP Cookies
Login.php
<?php
session_start();
if(login_success){
$_SESSION["active_user"] = "user-ID or Token";
}else{
//show login error
}
?>
Post.php
<?php
session_start();
if($_SESSION['active_user']){
// Check ID or Token to validate User
}else{
// redirect to login page
}
?>
I'm new to PHP. I have created a system where the users include user and admin. I login as a user in the system and the URL is localhost/View/user.php.
When I change the URL from localhost/View/user.php to localhost/Admin/admin.php, the user automatically has an admin interface.
My question is - how can I stop the user from being able to change the URL to /admin.php and accessing the admin interface?
Here are some examples:
http://php.net/manual/en/features.http-auth.php
But just know that this is not something you should use for a real website, unless you know all the security issues and how to solve them.
But for learning something about php and playing around this could be a place to start :)
Well you can't force a user to not modify the url in his browser.
What I think you are looking for is some kind of user roles.
So when you already have a login system I assume you store the username and password somewhere (mostly a database).
What you can do now is to add an additional field "roles" and write in "user", "admin" or something to differentiate users.
At your admin-page you could than check if the user has the role "admin", if not you can redirect the user to some other page (e.g. index) or just print out "Access denied"
(There are also a lot of tutorials about login systems and user roles for php out there. I would recommend to take a look at that also)
Simple add flag for user and check weather the flag is set or not if not than through user to error page.
Example
for admin $flag_admin=1;
and store this in session and check if flag is set than allow him to access admin screen else show error page.
A simple answer is that you should store the fact that the user has logged in via $_SESSION (such as $_SESSION['user_id'] = [something from the database]) and that can be tested later (such as isset($_SESSION['user_id']) followed up by looking that user up again in the database to make sure they do actually have admin rights. If they don't you can simply redirect them back to the login page via header('Location: http://whereever.com/login.php') or what-not. This isn't foolproof security, but it's a start.
If the session isn't automatically initialized (unlikely but possible depending on server configurations), you can start it at the beginning of each of your scripts with session_start().
To be more specific. Let's say that you have a script called user.php that takes in user login information. In that you might have something that looks like this...
<?php
session_start();
$login = (isset($_POST['login'])) ? trim($_POST['login']) : '';
$pass = (isset($_POST['pass'])) ? $_POST['pass'] : '';
if ($login !== '') {
$user = [db->lookup_somehow(where=>login is $login)]
if ([the hash of $pass is the same as the hash of the pass in $user]) {
$_SESSION['user_id'] = $user['user_id'];
header('Location: http://wherever.com/admin.php');
} else {
// say "invalid login"
}
} else {
// handle missing input
}
?>
And admin.php might look like...
<?php
session_start();
$user_id = (isset($_SESSION['user_id'])) ? $_SESSION['user_id'] : null;
$user = null;
if ($user_id) {
$user = [look up user from database based on their id];
if (!$user[has credentials to be an admin])
$user = null;
}
if (!$user) {
header('Location: http://wherever.com/user.php');
}
// else do admin stuff
?>
One possible solution to the problem is to check for admin permissions when the user navigates to the admin.php. If the user has adequate permissions, then the admin interface is visible. If the user does not have admin permissions, then they should be redirected back to user.php.
However, the better option would be to have a single login page - login.php. After logging in, the user permissions are checked, and the admin interface is made visible if applicable.
I have the proper solution.
suppose your admin's users id is 'admin' and your other users have other user id.
Then use $_SESSION('login_user') to login.
In your amdin page you want to protect from user you sholud put a condition that
$result = mysql_query("select username from adminlogin where username = '".$_SESSION['login_user']."'");
$result_value = mysql_fetch_array($result);
echo $result_value['username'];
if($result_value['username']!="admin")
{
header("Location: index.php");
}
Now it will check for user id = admin then it allow to access other wise it redirect the page to index.php that is our login page. If you can not understand then you can replay. Thanku
I used this to hide links until after the user is logged in, and was just wondering if this will cause any security issues or other issues in production code? I have been testing it and cannot find an issue so far as the website will not give a session_id until after the user logs on.
if(session_id()){echo ' EWO '...
There is no problem in this code until you put a session check also in the file
if session id is not set then send them back to home page.. Because if user knows the URL then they can navigate to the link
Make sure to add a function which will redirect the users to the login page as soon as the session gets destroyed i.e logout.
Also, as mentioned by #Saeed Ansari, add some logic to your project so only the login page is rendered when there is no active session or the user is not logged in.
HTH.
Either way, if your solution is to simply 'hide this link' until the user has logged in, this is not constructive code.
You should have a user object or user $_SESSION identifier registered in the session for when the user logs on.
For example. User logs on, you set a flag $_SESSION['Username'] = "Bob", where Bob is the user's username.
Then in your code, you could do something along the lines of:
if(array_key_exists('Username', $_SESSION)) { echo ' EWO '; }
Then when a user logs into your site successfully, register their username (atleast) in the $_SESSION, ie
$_SESSION['Username'] = 'Bob';
It is a good idea to have full control over your session by using session variables, rather than just relying on if a session has an ID.
It is never safe to assume, so I would also recommend (if you haven't done so) checking in the ewo.php file for the same thing ... check if the session has a registered Username/etc and if not redirect header('Location: /'); for example, to redirect the user back to the home page.
You could do it via a Session.
If you wanna check if the variable is set (User is logged in) in the session use:
<?php
session_start();
if (isset($_SESSION['username'])) {
echo "Your link here";
} else {
echo "login first";
}
?>
I am doing a web-application using PHP for job searching.
I have one query; when user is not logged in and wants to apply for the job given by clicking 'apply' button, he redirects to the login page. If the user is logged in when clicking, he should get directly to the application page. I'm not sure how to implement this.
I'm confused because I'm new to PHP.
Your question is very vague - maybe start with Authentication in PHP
Well, when the user clicks on 'apply' in your application the user is redirected to the login page if he is not logged in(which you can check if user session exists or not), remember when you redirect the page send the url of the current page in parameters to your login page so that when the user logs in he can be redirected back to the previous page and click on apply for that particular job.....
This is how the logic works, if you want the php, mysql explanation it would take some time for you to understand as you yourself conceded you are new to php..
You could store a value in the Session called "Login" and set this when the user logs in. This can also be used to re-direct the user if they haven't been logged in:
<?php
// check that the session variable does exist
// check that the user 'LoggedIn' has been set to 1 (true)
if (!isset($_SESSION['LoggedIn']) && $_SESSION['LoggedIn'] != 1)
{
// redirect to login page for user to authenticate themselves.
// pass page location (with parameters if necessary) to redirect
// the user on successful login.
header("Location: Login.php?redir=ApplyForJob.php?JobID=12345");
}
else
{
// user is logged in
// redirect the user directly to the apply for job page.
header("Location: ApplyForJob.php?JobID=12345");
}
?>
Can you, when the user logs in, assigns a $_Session variable to that user? i.e., after authentication, you set the $_SESSION['user'] variable.
$_SESSION['user']='admin';
So if you want to check whether the user is already log in after that, just use this:
if(isset($_SESSION['user']))
{
// user is login, direct to the job page
}
else
{
// no login, go to the login page
}
On each page set a cookie or session to which page they were just on:
$expire=time()+60*60*24*30;
setcookie("wherewasi","",time() - 1000);
setcookie("wherewasi",$_SERVER['REQUEST_URI'], $expire);
Then after login redirect them:
$loc = ($_COOKIE['wherewasi'])?$_COOKIE['wherewasi']:'index.php';
header("location: ".$loc);
exit();
There are two things that you need to worry about... checking that they've logged in, and then once they've logged in, directing them to the correct page.
This is all about 'saving state' across page requests. To do this you need can use cookies or more usefully sessions (which may be done via cookies or handled by the PHP engine for you automatically).
Sessions are probably a good way to go. To use sessions, every page needs to start with a
<?php session_start(); ?>
at the very least, before any html code that writes to the browser.
Once that's done you can use your the session variable to store
<?php $_SESSION['user']='joe_blow'; ?>
(and check)
<?php
if(isset($_SESSION['user']) && $_SESSION['user']!='' {
// do something
}
?>
whether the user is logged in, and which page they need to be redirected to after login.
<?php header("location: ".$_SESSION['redirect_location']));
But in order to write the any more useful code I think people would need to know what authentication method you were using... (How are you doing your login? Are you storing ID's in a database? Are you using an off-the-shelf package?)
After I authenticate user login info, i create this session for them:
$_SESSION['username']= $userName;
Then, I redirect them like this:
header('Location:www.domain.com/profile/' . $_SESSION['username'];
I want my website to have a beauty URL, something like: www.domain.com/profile/userName
Thus, in all my redirect links (HTML <a> tag or PHP header() function), I will use:
"www.domain.com/album/" . $_SESSION['username'];
Are there any security loopholes?
Edit:
Do I need to create session id first using session_id()?
So, to check:
if(!isset($_SESSION['id']){
//redirect to login page
}
Normally while using Sessions we also need to be aware of -:
Session Hijacking , Session Fixation
I suggest in your code after user logged in store the username in session variable also store one more unique value such as USER AGENT in a session variable. so that every page the user visit we can check for whether the same USER AGENT and SESSION ID exist this would make it much secure. To make it much more secure do the encryption like MD% on User AGENT so that hackers cant reproduce it.
Quoted from PHP SECURITY GUIDE
<?php
session_start();
if (isset($_SESSION['HTTP_USER_AGENT']))
{
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
{
/* Prompt for password */
exit;
}
}
else
{
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
}
?>
Refer :
PHP Security Guide on Session
Another Thread on Session security
What are you protecting? What are you doing to verify that they have authorization? Are you protecting their profile and verifying that they have authorization because they have the session key? You don't ever mention checking that they have a session variable.
You won't even need to know the session ID. That is immaterial to storing whether the user has gotten authentication, that's just the mechanism which indicates what session information they should be using.
When the user logs in, you want to store something like
$_SESSION['authed_user'] = true;
And then, on subsequent attempts to edit information you do:
if ($_SESSION['authed_user']) {
// do something authed users can do
}
And naturally, you'll really probably want some sort of levels of authorization. I recommend you consider using something like SimpleAuth...
You need authorization on the page that allows user to edit their profile. If they'll be editing on the http://www.domain.com/profile/[username] page then you need to check if their $_SESSION['username'] is equal to the profile page they are on.
Otherwise anyone would be able to type in the URL (basically guess a profile number or name) and edit it.
But yes, you should first check if they've logged in AT ALL:
if (IsSet($_SESSION['username'])) {
// Logged in
} else {
// Not logged in
}