php password protected website - php

I'm new to web programing and im trying to find a few good examples / tutorials on how to do a decent job of creating a website that requires users to log on to view any pages beyond the main log in page.
so far i've found 1 or 2 that ive tried but i keep running into the same problem. If i just enter the url of the page i want to see manually i can get in like there was nothing there.

Okay, I'll explain how the basic concept goes and a very simple implementation to get things going.
PHP (and most web applications) rely on RESTful services -- which, to our concern at the moment, means every request is not remotely bound to any other request being made - either that being by the same user or others.
So what does that mean?
This means that for every single request, you need to do your checks. You need to make sure if the user has permissions to execute that page, or less severely even see its contents.
How is this achieved?
By many ways, actually. There are lots of techniques used to enforce authorization on web applications but they would essentially both break down to one of two -- either centralized, or decentralized.
-- Centralized
This means all your actions (and controllers) are being handled through a single file. Say index.php. This file would then include or delegate its tasks to other files (that are not runnable on their own via normal requests) based on request parameters. This is a very popular approach, but not exactly straight forward for new developers. Examples of applications that use this approach would have URLS of the type: index.php?do=register, index.php?do=login, index.php?do=showtopic&topic_id=2, and so forth.
A simple implementation of this technique would go like:
<?php
// index.php
define('RUNNING_APP', true);
// 1. place your auth code here, or...
switch ($_REQUEST['do']) {
case 'register':
// 2. or here
include 'inc/register.php';
break;
case 'do_register':
// 2. and here, and before every include.. and so forth.
include 'inc/do_register.php';
break;
}
?>
<?php
// inc/register.php
defined('RUNNING_APP') or die('Cannot access this script directly'); // make sure to break direct access
?>
<form action="index.php?do=do_register">
<!-- form elements -->
</form>
and so forth.
I've documented where the usual auth code should go.
-- Decentralized
Using this approach, however, your auth code should go at the beginning of every single file. URLS of applications of this sort usually look something like: register.php, login.php, and so forth. The main problem here is that you need to perform all auth logic per file, as stated above, and that may be a hectic job if your files increase in amount. A convenient solution is to have that logic in a single file, and include that file (which would kill the request for unauth personel) before any of your logic. A simple example would be:
<?php
// index.php
include('inc/auth.php');
// index logic
?>
<?php
// register.php
include 'inc/auth.php';
// register logic
?>
<?php
// inc/auth.php
$logged_in = false;
if (!$logged_in) {
die ('You do not have permission to access this page. Please login');
}
?>

When logging in using a form, you should check the username and password in the database. The password should be scrambled (usually done using the MD5 hash algorithm), and stored in the database in the same way. You capture the variables, using something like (use some validation to check if the POST variables are valid):
$username = $_POST['username'];
$passwordHash = md5( $_POST['password'] );
The username and hashed password should be stored in your database. You can then check for a match in the database using:
$res = mysql_query("SELECT * FROM users WHERE username='".$username."' && password='".$password."'");
When a user is found, you use sessions to store the user values, which will allow you to get access to a users information across pages. NOTE: session_start() is usually placed at the top of the page, but I'll place it here for readability.
if ( mysql_num_rows($res) ) {
session_start();
session_regenerate_id(); // regenerate session_id to help prevent session hijacking
$row = mysql_fetch_assoc($res);
$_SESSION['logged_on'] = true;
$_SESSION['username'] = $row['username'];
// add more session variables about the user as needed
}
On every page you want to protect, you add the following to the top of those pages:
session_start();
if ( !isset($_SESSION['logged_on']) ) {
header("Location: login.php"); // user is not logged in, redirect to login page
exit;
}
// page content here

There's HTTP Auth:
http://php.net/manual/en/features.http-auth.php
Or you can roll your own with a login form and session tracking:
http://www.php.net/manual/en/book.session.php.
Http auth means the user gets a pop-up dialog window asking for a username and password, it's less usual than the self-rolled version.
Enjoy!

The sites you mentioned are likely bypassable because the pages past the security check don't save and then check for login status on each page. You need to check that a visitor is logged in before access to a page is granted.

I think most users would expect form input for a login. If you want the user to come back and log in with the same account later after their session expires, you'd need a database to store user information.
When storing user information in a database, you should probably not actually store their password, either. For an example:
name password ...
-----------------------------------------------
Johnny '3858f62230ac3c915f300c664312c63f'
Alice '80338e79d2ca9b9c090ebaaa2ef293c7'
.
.
.
Johnny's password is actually "foobar", but the database stores md5('foobar'). When Johnny tries to log in, he enters his username ('Johnny') and his password ('foobar'). In PHP, you hash the password he entered, and call up his password value from the database, resulting in:
if (md5('foobar') == '3858f62230ac3c915f300c664312c63f')
This conditional is true. You can confirm if he logged in correctly, but you're never storing his actual password.
Alice's password is 'foobaz'. She tries to log in, but accidentally types 'foobar', Johnny's password. this results in:
if(md5('foobar') == '80338e79d2ca9b9c090ebaaa2ef293c7')
Which is false. Again, you don't know what Alice's password is, just that she entered the wrong one.
The downside to this strategy, of course, is that you can't tell the user what their password is when they forget it -- you don't know! You can resolve this by letting a user reset their password (to some semi-random string) instead of strait telling them what their password is.

Related

Set and Check Cookie in the one response - Laravel

I am attempting to set a cookie and then check to see if the cookie has been set.
So in one function, I have it make the cookies:
public function makeCookies(){
Cookie::queue('logged_in', $value, 15);
Cookie::queue('user_id', 2);
//return Response::make()->withCookie(Cookie::make('logged_in', $value, 15))->withCookie(Cookie::forever('user_id', 2));
}
And in the other function, I try to check to see if the cookie has been set:
public function checkCookies(){
$this->makeCookies();
if(Cookie::get('logged_in') && Cookie::get('user_id')){
return 'Logged In!';
}
}
However the only way this works is if I add 'return' before $this->makeCookies(); However, I want to be able to get to the conditional below it. Is there any way I can go about doing this? Any help is greatly appreciated.
To understand the Cookie Creation/Read process:
The user's browser sends a request for a page, along with any cookies that it currently has for the site
The site serves up the page, and any cookies you create become a header in your response.
Subsequent requests to your site will send the cookies created in #2.
What you are asking...to be able to read cookies that you create in step #2 in step #1...not possible.
Now, depending on how the Cookie class is created, you could make it so that when the Cookie::queue() is called, that it creates in-memory data that reflects what the cookie "should be" on the next request, but it doesn't truly know whether or not the user's browser will accept cookies, etc.
This is why many sites, after creating a cookie give the user a redirect to a page with something like ?checkCookie=1. This way, on the subsequent request, they can verify that your browser supports cookies...and if the cookie doesn't exist on the ?checkCookie page, they give you an error saying that their site requires cookie support. However, it does require a second round to the server to read cookies from the browser that were created.
UPDATE 2015-04-24 Per #Scopey, Laravel does support in-memory retrieval of cookies via queued(). So, you should be able to do:
public function checkCookies(){
$this->makeCookies();
$loggedIn = Cookie::get('logged_in') ?: Cookie::queued('logged_in');
$userId = Cookie::get('user_id') ?: Cookie::queued('user_id');
if( $loggedIn && $userId ){
return 'Logged In!';
}
}
SECURITY CONCERNS (NOT DIRECTLY ANSWERING THE QUESTION)
Your question was only about the cookies, so that's all I answered. However, now that I'm looking at your code, I feel I would be remiss not to point this out for anyone that happens to be reading this. This may just be a "how to" for yourself and not production code, but that code could be very dangerous if it ever went public.
Make sure you do NOT TRUST a user_id stored in a cookie to determine what user is coming in via cookies. If you rely on that, and I come to your site, I can modify my cookie to any user_id I want and get into other people's accounts.
General Safety Rules:
A cookie should contain a GUID, or similar random string to identify the session. This random string should be sufficiently long (e.g. 32 characters or greater, IMHO) that it is not easy for someone to brute-force their way to hijacking sessions.
The user_id should be stored in the $_SESSION (or laravel's wrapper for session if applicable) so that the user doesn't have any access to the user_id to be able to modify it.
In plain PHP, this something like this for the login page:
session_start();
if( isValidPassword($_POST['username'], $_POST['password']) ) {
$_SESSION['user_id'] = $user->Id;
}
else {
die('invalid login credentials');
}
The session_start() method automatically generates a cookie for the user with that long, random string (so you don't even have to worry about that part.)
On subsequent pages, you just check the session user_id to know who is logged in:
session_start();
if( empty($_SESSION['user_id']) ) {
die('You are not logged in and cannot access this page');
}
Change as needed per Laravel's documentation, which if they have their own session wrapper, I'm sure is well documented on best practices.
Excellent description by #KevinNelson about cookies but Laravel does support fetching back any cookies you have queued in the current request. Try using
Cookie::queued('logged_in');
The catch is, the cookie will only be "queued" during the request that you queued it. You will have to use get like you are for any other requests.

Redirect loop on login script PHP

I have a login system that whenever the user logs succesfully creates some cookies with his username password and some other variables that are put in the url for configuration of the session:
setcookie("username", $myusername); //Sets a cookie storing the username
setcookie("password", $mypassword); //Sets a cookie storing the encrypted value of the password
setcookie("typeOfUser",$type); //example variable
and the variables are passed through the URL:
header("location:http://www.example.com/logged.php?type=".$type);
inside the logged.php page I have a file called protect.php which checks whether the cookies exist and what kind of user is it.
if(isset($_COOKIE["username"])&&isset($_COOKIE["password"])){
//check if this user's cookies exist on the DB
$user = $_COOKIE["username"];
$pass = $_COOKIE["password"];
$sql="SELECT * FROM USERS WHERE Usr='".$user."' and Pass='".$pass."';";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1){
$type = $_COOKIE["type"];
header("location:logged.php?type=".$type);
exit();
}
else{
header("location:http://www.example.com/login.php");
}
}
so if the user just types www.example.com/logged.php he/she will get the variables associated with his user, but whenever I do this I get a redirect loop on the site. (It seems to me a little bit obvious that it redirects cause each time it goes to the header("location... it restarts and at the top it checks the protect.php... but I can't figure out a way to solve this).
Note logged.php just has at the top an:
include("protect.php");
Thanks in advance!
The reason that this script loops infinitely is based in the logic:
if($count==1){
header("location:logged.php?type=".$type);
}
else{
header("location:http://www.example.com/login.php");
}
Regardless of the value of $count at this point, your script will send a location header. In other words, the browser is receiving a redirect either way, whether $count is equal to 1 or not.
if(isset($_COOKIE["username"])&&isset($_COOKIE["password"])){
In combination with this line, your loop is defined. This evaluates to true if the user has these cookies defined, which happens when they are logging in for the first time, or have already logged in. If they are logged in, their username and password must be valid, and $count will end up as 1, because they are in the database.
In short, every time the user goes to logged.php after they are logged in, this script is run because they have the appropriate cookies and they are directed, again, to "logged.php?type=."$type" (over and over again) because they are a valid user and present in the database.
To fix this, you'll want to stop header("location:logged.php?type=".$type); from running every time protect.php is run. This is the essence of your problem. You can fix this however you like, but I would do it with sessions.
Check out this tutorial to learn how to implement sessions in your logins script.
You already have three cookies: username, password, and typeOfUser. The system you have works fine, but most authentication scripts use sessions, accessible like cookies ($_COOKIE['foo']), but with the $_SESSION variable instead. The advantage to using session is that the values you store in them are not available to anyone but scripts on your server/site, to view, or to edit. In general, the less information you expose to the user, the better. If you need clarification, check out this StackOverflow post or the basic examples on the PHP website.
One more thing to point out is in your script, if(isset($_COOKIE["username"])&&isset($_COOKIE["password"])){ has no else statement. If one or both of these cookies are not defined, no code will be executed, and what I am assuming is a protected page will be displayed publicly. You may want to add an else statement, something along the lines of:
else{
header("location:http://www.example.com/login.php");
}
Hope you're able to make this functional and awesome!

best and secure way to authenticate user in php application

I need to know how secure is my user authentication code that I am using in my php applications.
This is my login check function
// Is Login
//*********************************************************************************
public function isLogin()
{
$validation = new Validation();
if(!$validation->isEmpty($_SESSION["AdminId"]) && !$validation->isEmpty($_SESSION["AdminUsername"]) && !$validation->isEmpty($_SESSION["AdminName"]))
{
return true;
}
else
{
return false;
}
}
I have a authenticate file which i call from top of every user account's page which is as under
if (!$admin->isLogin())
{
header("Location: index.php?type=warning&msg=" .urlencode(ADMIN_INVALID_LOGIN));
exit();
}
The session values for example Adminusername is the actual username of the admin, adminname is the alphabetical name of the admin and adminid is the record id from mysql table such as $_SESSION["Adminusername"] = administrator though i am storing this value after encypting it.
I need to know is this a secure method to just store the values and check for them or I need to have some kind of advance functionality to make it more secure such as salt or time check etc.
I would appreciate your suggestions and feedbacks. If possible, your authenticate code / class.
Thanks in advance.
Amardeep Singh
use session regenerate id to get a new ID in every request, so u can prevent session hijacking .. read this manual : http://php.net/manual/en/function.session-regenerate-id.php
I am storing this value after encypting it
I don't understand... Why do you crypt your AdministratorName?
As you surely know, the user cannot manipulate his session as he wants, because the session is on the serverSide and your code decide what to write into session-data.
I think, salting or timechecking do not raise your security-level.
Because HTTP is stateless, each session is identified by a id, which ist mostly saved in a cookie on the client side. Each of your request to this server contains this SID, because it's the only way your server could identify a visitor.
If you use HTTP-Transport, your data (end also your SID) is sent through the internet without encryption. So a hacker could read your SessionID and take over your Session (which contains logged in User-Data). To prevent this, you can force HTTPS connection for logged in users.
If you have the possibility to switch all your pages to https-only, do it. If you must switch between http and https (for example https only if user is loggedin) it becomes really difficult to guarante security!

Force user to logout session PHP

I can't seem to find a straightforward answer to this question. Is there a way in which I can force a logged in user to logout? My login system essentially just relies on a session containing the user's unique ID (which is stored in a mysql database). So essentially just...
if (isset($_SESSION['user_id'])) {
echo "You're logged in!";
} else {
echo "You need to login!";
}
But let's say I want to ban this user, well I can change their status to banned in my database but this won't do anything until the user logs out and attempts to log back in... So, how do I force this user to logout? Preferably without checking every single time they view a page whether or not their status has been switched to "banned" because that seems like unnecessary stress on my server. Any help is appreciated, thank you.
Either you need to check every time they load a page, or possibly look at an Ajax call at set intervals to check their status from the DB.
Then you can use session_destroy(); to end their session. This will destroy their entire session.
Otherwise you can use unset($_SESSION['user_id']); to unset a single session variable
Preferably without checking every single time they view a page whether or not their status has been switched to "banned" because that seems like unnecessary stress on my server.
Loading the user from the database on every page load, rather than storing a copy of the user in the session, is a perfectly reasonable solution. It also prevents the user from getting out of sync with the copy in the database (so that, for instance, you can change a user's properties or permissions without them having to log out and back in).
Try to put this on every page...
if (isset($_SESSION['user_id'])) {
$sql = "SELECT from tbl where status='banned' and user_id=$_SESSION['user_id'] ";
$query = mysql_query($sql);
if(!empty(mysql_num_rows($query))){ // found the banned user
//redirect to logout or
//session_destroy();
}
} else {
echo "You need to login!";
}
if the user is still logged in... check if his/her status is banned or not... if banned.. then logout
You can unset it.
unset($_SESSION['user_id'])
You could use Custom Session Handlers this way you have full control where and how the session data is stored on the server.
So you could store the session data for a particular user in a file called <user_id>.session for example. Then, to logout the user, just delete that file.
Ajax calls in an interval will put extra load on server. If you want real-time response to your actions(e.g. the user will be signed out right when you ban them from your system backend), then you should look into something like Server Push.
The idea is to keep a tunnel open from Server to Browser whenever a user is browsing your website, so that you can communicate with them from server-side too. If you want them to be banned, push a logout request and the process that in your page(i.e. force logout by unsetting session).
This worked for me am using pHP 5.4
include 'connect.php';
session_start();
if(session_destroy())
{
header("Location: login.php");
}
You can use session_save_path() to find the path where PHP saves the session files, and then delete them using unlink().
Once you delete the session file stored in the sever, the client side PHPSESSID cookie will no longer be valid for authentication and the user will be automatically be logger out of your application.
Please be very careful while using this approach, if the path in question turns out to be the global /tmp directory! There's bound to be other processes other than PHP storing temporary data there. If PHP has its own directory set aside for session data it should be fairly safe though.
There is a few ways to do this the best in my opinion based on security is:
NOTE: THIS IS REALLY ROUGH.... I know the syntax is wrong, its just for you to get an idea.
$con = mysql_connect("localhost","sampleuser","samplepass");
if (!$con)
{
$error = "Could not connect to server";
}
mysql_select_db("sampledb", $con);
$result = mysql_query("SELECT * FROM `sampletable` WHERE `username`='".$_SESSION['user_id']."'");
$userdeets = mysql_fetch_array($result);
if($_SESSION['sessionvalue'] != $userdeets['sessionvalue'])
{
session_destroy();
Header('Location: logout.php');
}
else
{
$result2 = mysql_query("UPDATE `sessionvalue` WHERE `username`='".$_SESSION['user_id']."' SET `sessionvalue` = RANDOMVALUE''");
$sesval = mysql_fetch_array($result2);
$_SESSION['sessionvalue'] = $seshval
}
Now I know thats not the very code but in essence what you need to do to be secure and have this ability is:
Everytime a page load check a Session value matches a value in the DB.
Every time a page loads set a new session value based on a random generated DB value. you will need to store the username in a session as well.
if the Session ID's do not match then you destroy the session and redirect them.
if it does match you make the new session ID.
if you want to ban a user you can set their sessionvalue in the DB to a value like "BANNED". this value will not allow them to log in either. this way you can control user through a simple web form and you can also generate list of banned users very easily etc etc. I wish I had more time to explain it I hope this helps.

PHP Class Scope

I am fairly new to PHP. What is the best way to control access to a class throughout a PHP application and where is the best place to store these classes that will need to be accessed throughout the entire application? Example; I have a user class that is created on during the login process, but each time the page post it appears that the object is reinitialized.
I have tried to set property IsLoggedIn and then check that variable each time before creating the object as new again, but this doesn't seem work. I have also tried to use the isSet function in PHP to see if the class variable already exists
You're right, the state of your application is not carried over from request to request.
Contrarily to desktop applications, web applications won't stay initialized because to the server, every time it can be a another visitor, wanting something completely different. You know who's using the desktop application, but you don't necessarily know who's requesting the page. Imagine 10 users doing different thing simultaneously on your web application? You wouldn't keep the whole application running necessarily for each of those visitors. Imagine with 10,000 visitors...
There are ways to keep some data from request to request though. The application will be reinitialized each time, yes, but you can then reload the state of what you were doing. It always revolve around around the same general methods:
Cookies; Cookies are a small file that is kept on the client side and which content will be available on each request to you. In PHP, this is available using $_COOKIE variable. In all cases, you could serialize your classes instances and reload them afterwards. The problem is, you wouldn't want to put sensitive data there as any(malicious)body can see and modify it.
POST or GET; In each request, you pass a state in the $_GET request (the URL such as http://localhost/myscript.php?iamatstep=4. Or via a $_POST such as using a hidden input field in a form. This data could be encrypted and make sense only to you, but still, you are putting sensitive data back to the client and anybody could fiddle with it.
Database, Disk; Or anything else on the server. Again, you serialize your data in a file for example at the end of a request ready to be used again for the next request. The main advantage is that it stays on your server. The downside is that at this point, you don't know which data to extract back for which request as there might be multiple users on your application at the same time...
And this is where the notion of $_SESSION comes into play. It's just a packaged way of using all of this at the same time. It's not magical as often it's perceived by beginners. When you use a session, the data put into the $_SESSION is stored somewhere on the server (normally a file in a temporary directory although it can be changed to something else like a database) and a unique ID is attributed to this session and passed in a cookie that will follow the visitor from request to request. So the only thing on the client's side is a big number in the cookie. On the next request, the browser tells PHP on the server that it's session number 12345, loads the corresponding file if it exists and then the data is available to you again. If cookies are not enabled, it could be passed in a GET or POST, although it's often better not to go there (see session.use_trans_sid's note).
It often looks like that on each of your pages you need authentication.
<?php
// verify if we have a current session
if (isset($_SESSION['login'])) {
// get data in current session
$username = $_SESSION['login']['username'];
$isLoggedIn = $_SESSION['login']['isLoggedIn'];
} else {
$username = '';
$isLoggedIn = false;
}
// take care of the unauthorized users
if (!$isLoggedIn) {
// maybe a redirection here...
}
// do the things a logged in users has the permission to do
And to set the session, it'll probably look like that:
<?php
// handle the form post of your login page for example
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// verify the username and password against a database
if ($everythingIsOkay) {
// we can consider this user logged in and create a session
$_SESSION['login']['username'] = $username;
$_SESSION['login']['isLoggedIn'] = true;
// and now maybe redirect the user to the correct page
}
}
// raise an error about an invalid login
And finally, maybe a logout.php page that would do something like that:
<?php
unset($_SESSION['login']);
// redirect the user to the login page
This kind of data is going to have to be stored in a session, the only thing that is carried from page to page is Session data (sessions/cookies/...) so your class initialization is not carried over.
You can add information like the users username to the session with:
$username //username from db
$name //name from db
$_SESSION['username'] = $username;
$_SESSION['name'] = $name;
or if you just want to have easy access to all the information about the user you can do:
$_SESSION['user'] = mysql_fetch_assoc($result); //where $result is the response from the db to your login query
after you do this $_SESSION['user'] will be an array with all the details you selected from the database.

Categories