How to prevent user from bypassing php authentication - php

We call it html1 for simplicity.
When a user goes to html1, there's a login2.php login page to enable access to client.php which is the hidden page.
It then goes to checklogin.php...if the password and user name matches...it then goes to the hidden client.php page...if not..it goes back to homepage.
The user has to login to be able to view the contents of hidden client.php page.
However the user can access client.php by typing in ..../client.php on the address bar...therefore bypassing the auth page and rendering it useless. I can just type servername/client.php...and it still shows me the contents of client.php...but I want client.php...to be private!
How do I prevent this from happening?
thanks.
first login page...
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<table>
<form method="post" action="checklogin2.php">
<div id="name">User Id: <input type="text" name="****"></div>
<div id="password">Password: <input type="password" name="*******"></div>
<div class="button"><input type="submit" value="Login"></div>
</form>
</table>
</body>
</html>
then it goes to....
checklogin2.php
<?php
$*** = $_POST['****'];
$***** = $_POST['***'];
if($uid == '****' and $***** == '*****')
{
session_start();
$_SESSION['sid']=session_id();
header("location:securepage.php");
}
else
{
header("location:index.html");
}
?>
Then it goes to...
securepage.php
<?php
session_start();
if($_SESSION['sid']==session_id())
{
header("location:client.php");
echo "<a href='logout.php'>Logout</a>";
}
else
{
header("location:login.php");
}
?>

In the beginning of your every page you have to check if user is authorized.
On checklogin.php if user entered correct login and password, just set something like
$_SESSION['authorized'] = TRUE;
...and on other pages just check if user is authorized:
if (isset($_SESSION['authorized']) && $_SESSION['authorized'] === TRUE) {
// Alright, let's show all the hidden functionality!
echo "Psst! Hey! Wanna buy some weed?";
} else {
// User is not authorized!
header('Location: login.php');
exit();
}
Note that you don't have to mess with cookies, session IDs etc. - just add session_start() before everything and freely use $_SESSION var.
This is the main pro of sessions (and $_SESSION variable in particular): you can remember some data among different pages on same website.

All pages has to check if the user is authed. I would recommend using objects, and always inherit a class that checks this for you. It's not fun to have the same code everywhere, doing the same thing.

if($_SERVER["PHP_SELF"] == '/yourpagefolder/yourpage.php' && !isset($_SESSION['login_user'])){
header('location: login.php');
}

Related

Login implementation in PHP

Suppose, I have two pages login.php and index.php. In index.php I have two buttons Login and register.After clicking the buttons ,the user is directed to login.php.
If I want to implement a login functionality using PHP, something related to facebook such that the if a user has logged in before, then it bypasses the index page once the username and password are set and directly lands into the login page. Is $_SESSION a proper way of doing it.
For example:
<?php
session_start();
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ayu</title>
</head>
<body>
<?php if (isset($_SESSION["user"])) { ?>
<h1>Hi <?php echo $_SESSION["user"]; ?></h1>
Logout
<?php } else { ?>
<h1>Login</h1>
<?php echo (isset($_GET["error"])) ? '<p>You idiot!</p>' : ""; ?>
<form action="new-user.php" method="post">
<div>
<label>
<strong>Username</strong>
<input type="text" name="username" />
</label>
</div>
<div>
<label>
<strong>Password</strong>
<input type="password" name="password" />
</label>
</div>
<input type="submit" value="Log In" />
</form>
<?php } ?>
</body>
</html>
In the login functionality, I am setting the $_SESSION values
<?php
session_start();
if (count($_POST))
if ($_POST["username"] == "ayu" && $_POST["password"] == "shee") {
$_SESSION["user"] = "Ayushi";
header("Location: ./");
} else {
unset($_SESSION["user"]);
header("Location: ./?error");
}
?>
Yes using and creating ($_SESSION) session is the correct way to check logged in users.
$_SESSION is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a script.
There is no need to do global $variable; to access it within functions
or methods.
Check for session on very top of a page, if found redirect to index else to login page.
if(!isset($_SESSION['login_user'])){
header("location:login.php");
}
Refer this simple login example using my sql in php Here
EDIT
As requested by OP - if you want to hide a particular section in index.php page based on session value or say if a user is logged in or not that can be done like:
<?php
if(isset($_SESSION['login_user'])){
?>
<form>
<input type="submit" name="whatever" />
<!-- Other Fields -->
</form>
<?php
}
?>
Html Form in the above code will only be shown if a user is logged in else it will be hidden.
Yes, Session is best way to implement the same. You can use the below php code to solve your problem
<?php
session_start();
if (!empty($_POST))
if ($_POST["username"] == "ayu" && $_POST["password"] == "shee") {
$_SESSION["user"] = "Ayushi";
header("Location: ./");
} else {
if($_SESSION["user"]!=''){
unset($_SESSION["user"]);
}
header("Location: ./?error");
}else{
/* Write code for form */
}
?>

Building login secured php scripts

So I'm trying to make a secure homepage that checks if you're logged in by getting the text that the user entered on the login page and checking they are correct (so you can't just do www.website.com/home.php to bypass login)
<body onload="OpenPhp()">
<form name="GetLogin" action="GetIfLoggedIn.php">
</body>
The script is :
<script>
function OpenPhp(){
document.GetLogin.submit();
}
</script>
the php script should include the username and password vars from the login script and re-check them
<?php include "Login.php";
if($Username === "*****" and $Password === "******"){
// Return To Page
}else{
//Go Back To Login Page
}
?>
But the include statement makes the home page inaccessible. Every time I go to the home page it just sends me back to the index.html page.
Are there any better ways to secure a web page? If so please tell me or explain why this doesn't work,
For securing a webpage i encourage you to work with sessions.
You use one script (lets call it login.php) to allow the user to login. If the login is correct you store the username as a session variable.
In your secured pages you just check if the username is set in the session.
In all your scripts you need to execute session_start(); to make the $_SESSION superglobal variable available.
For logging out you can just destroy the users session using session_destroy();
Examples:
login.php:
session_start();
function isValidLogin($username_, $password_)
{
if($username_=='sam' && $password_=='secret')
return true;
return false;
}
if(isValidLogin($username, password))
{
$_SESSION['username']=$username;
}
your_secured_page.php:
session_start();
if(isset($_SESSION['username'))
{
// display page
}
else
{
// redirect to login.php
}
logout.php
session_destroy();
Another tutorial i found:
http://www.formget.com/login-form-in-php/
You Might Wanna Use This.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Fetch Array Trick</title>
</head>
<body>
<?php
$con = mysqli_connect("localhost","root","","lesson") or die("Connection Not Established");
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$username = $_POST['username'];
$password = $_POST['password'];
$get=array("0"=>$username,"username"=>$username,'1'=>$password,"password"=>$password);
//Created an array above that matches username and password.
$lol = mysqli_query($con,"Select username,password from users");
while($pre= mysqli_fetch_array($lol)){
//Now we check if, while in the loop, any tuple matches
if (($get == $pre)){
echo '<h1><font color=green>Found</font></h1>';
//Use JavaScript To Redirect or clear headers to use header("location: dashboard.php");
exit;
}
}
echo '<h1><font color=red>Not Found</font></h1>';
}
?>
<form action="" method="post">
<p><label for="u">Username</label><input type="text" name="username" id="u"></p>
<p><label for="password">Password</label><input type="password" name="password" id="password"></p>
<p><input type="submit" name="submit" value="Login" id="submit"></p>
</form>
</body>
</html>

Bug using PHP Sessions (Two Log On screens)

In the application I'm developing I'm having a bug where I direct my browser to my app's index.php, and is then properly redirected to login.php if there is no current session. My problem is that after I type in my correct details on login.php and click submit, I am linked to another login.php screen (instead of returning to index.php with an active session) and required to put in my details again. The first screen has the same CSS formatting as index.php, while the second screen doesn't.
After entering my details on the second screen and clicking login, the sessions seem to function normally. Also, many times I will be presented with one logon screen, ill login and the user's correct Home screen data will be displayed (which requires successful queries from the login data), but if I navigate away from index.php to another screen that requires an active session, it will present the unformatted login.php screen.
If I logout, navigate to a different non-restricted page, and attempt to log back in again within the same browser session, the logon functions correctly with only one screen.
Here are snippets from the relevant files:
index.php
<?php
include_once 'db_functions.php';
require_once 'access.php';
if (isset($_POST['action'])) {
if (userIsLoggedIn()) {
header('Location: http://www.myapp.com/index.php'); //prevents users from having to confirm form resubmission if they refresh the page
}
}
if (!userIsLoggedIn()) {
include 'login.php';
exit();
}
login.php:
login.php
<body>
<h1>Log In</h1>
<?php
if (isset($loginError)) {
echo $loginError;
}
?>
<form action="" method="post">
<div>
<label for="email">Email: <input type="text" name="email" id="email" /> </label>
</div>
<div>
<label for="password">Password: <input type="password" name="password" id="password" /></label>
</div>
<div>
<input type="hidden" name="action" value="login" />
<input type="submit" value="Log in" />
</div>
</form>
</body>
access.php:
<?php
function userIsLoggedIn() {
if (isset($_POST['action']) and $_POST['action'] == 'login') {
if (!isset($_POST['action']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '') {
$GLOBALS['loginError'] = 'Please fill in both fields';
return FALSE;
}
$email = $_POST['email'];
$password = $_POST['password'];
if (databaseContainsAuthor($email, $password)) {
session_start(); //LINE 17
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
return TRUE;
}
else {
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
$GLOBALS['loginError'] = 'The specified email address or password was incorrect.';
return FALSE;
}
}
if (isset($_POST['action']) and $_POST['action'] == 'logout') {
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
header('Location: ' . $_POST['goto']);
exit();
}
session_start();
if (isset($_SESSION['loggedIn'])) {
return databaseContainsAuthor($_SESSION['email'], $_SESSION['password']);
}
}
function databaseContainsAuthor($email, $password) {
include_once './db_functions.php';
$db = new DB_Functions();
$result = $db->accountExists($email, $password);
return $result;
}
?>
Any help would be greatly appreciated!
UPDATE:
Error logs are showing multiple occurances of this error:
PHP Notice: A session had already been started - ignoring session_start() in /home3/monitot5/public_html/app/access.php on line 17
Access.php line 17:
if (databaseContainsAuthor($email, $password)) {
session_start(); //LINE 17
$_SESSION['loggedIn'] = TRUE;
What you should do is to use
session_start();
at the beginning of access.php file and don't use this function any more.
You should also completely change login of your access.php file. The first thing you should always do in this file is checking if there's a valid session for this user. Now you check it at the end of file and probably earlier you clear it because you unset session if there are no $_POST data.
In addition you shouldn't also use password in your session. It's rather very insecure. You should simple store login for your system when user filled in form valid username/email and password and unset it if user has logged out.
Sorry, but I won't write the whole code for you. You should simple look at some examples of code in Google to check how to handle user login/logout in PHP.

PHP Session won't keep array variables

I have an Index page with login form, a verification page called Login and content.
Index is fairly simple: if logged in, redirect to Content, otherwise display login form and POST to Login page
index.php:
<?php
session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd'])){
header('Location: content.php');
} else {
?>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> PHP Login </title>
</head>
<body>
<center>
<form method="POST" action="login.php">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="usr"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pswd"></td>
</tr>
<tr>
<td><input type="submit" name="login" value="Login"></td>
<td><input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
<?php } ?>
Then we have Login verification: compare the POST vars with coded variables, if all is good, set Session variables and redirect to content.
login.php:
<?php
session_start();
if($_POST['usr']=='user' && $_POST['pswd']=='password'){
$_SESSION['usr'] = 'user';
$_SESSION['pswd'] = 'password';
header('Location: content.php');
} else {
echo "post: ";
print_r ($_POST);
//header('Location: index.php');
}
?>
Then we have the Content page, check that the Session is set and display content, otherwise PRINT_R
content.php:
<?php
session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
} else {
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>
The process works, up to the Content page. I keep getting a blank SESSION array, and when I try going to Index, it pretends I never logged in. what am I missing?!
Edit: in The code above, content.php is trying to check if the session is set. If it is NOT set it will show me a blank array (for debugging purposes, but normally I want it to go back to index, since the user is not properly connected),
if it IS set, it will echo "you are logged in". It is also including a page called 'logoff.html' as that page has a button to destroy the session.
Even without the IF statement, simply running a print_r ($_SESSION); returns a blank array. This means there is no problem in the IF statement, but something that happens before it.
Solution: I didn't know about this before, but some hosting sites require some PHP set up, before they can store PHP sessions. I went to the knowledge base of my hosting service and searched for "session", and found an explanation on how to set up the php.ini file to save my sessions in the correct path.
Make sure sessions are configured properly. For example, is the session save handler set correctly? If using files, does it have permission to access the specified folder? If memcache, is that set up properly?
This would be the main reason for session variables to not be saved.
change this
<?php
session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
} else {
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>
i think in your code when session not set then it will print so change it with
<?php
session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd']))
{
// session is set
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
}
else
{
/// session is not set
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>

How to stop people accessing hidden pages where a login is required?

I am doing a project in school, I need to know a simple way to stop poeple from entering the site without a session. I have alot of pages I don't believe I spent the time pasting code on every page. Also I have menu bar that is included in every page thanks to php, so i was wondering wat type of code would I have to put in the menu to block user without a session. The rest of the content code is on the pages that I want to hide. I believe that you can login by typing out the url and allow users to see hidden pages that are for logged in users.
Please do not use a plain cookie. Sessions are the way to go. Or if can't use sessions and must use a cookie, sign the cookies first to be able to verify that your application was really the one to set it.
<?php
session_start();
if (!isset($_SESSION['authenticated'])) {
header('Location: login.php');
exit;
}
... whatever logged in users should see ..
If you don't want to use session, then use cookie.
<?php
/*Just add this piece of PHP code to top of any page you
don't want not-logged in users to see */
if (!isset($_COOKIE['logged']))
header("Location: login.php"); //It redirects the user to your login page
?>
<html>
<body>
...
</body>
</html>
Login page could be like this:
<?php
if (isset($_COOKIE['logged']))
header("home.php");
if ($_POST['submit']) {
//get username and password
$uname = $_POST['uname'];
$pass = $_POST['password'];
if ($uname=="correct" && $pass=="correct"){ //EDIT
setcookie('logged','1');
header("Location: home.php"); //Redirect to home page
}
else echo "Wrong combinaton!";
}
?>
<html>
<body>
<form action="login.php" method="post">
<label>Username</label><input type="text" name="uname" /><br />
<label>Password</label><input type="password" name="pass" /><br />
<input type="submit" name="submit" value="Login" />
</form>
</body>
</html>

Categories