How to make a page accessible only after log in - php

here is my login page:login.php
<?php
require_once('connectvars.php');
//start the session
session_start();
//clear the error message
$error_msg="";
//If the user isn't logged in ,log them in
if(!isset($_SESSION['user_id']))
{
if(isset($_POST['submit']))
{
//connect to database
$dbc=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$user_username=mysqli_real_escape_string($dbc,trim($_POST['username']));
$user_password=mysqli_real_escape_string($dbc,trim($_POST['password']));
if(!empty($user_username)&&!empty($user_password))
{ $query="select user_id,username from gyan_userdata where username='$user_username'and password=SHA('$user_password')";
$data=mysqli_query($dbc,$query);
if(mysqli_num_rows($data)==1)
{
$row=mysqli_fetch_array($data);
$_SESSION['user_id']=$_row['user_id'];
$_SESSION['username']=$_row['username'];
setcookie('user_id',$_row['user_id'],time()+(60*60*24*30));
setcookie('username',$_row['username'],time()+(60*60*24*30));
$home_url='http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/index2.php';
header('Location:'.$home_url);
}
else
{
$error_msg ='<p>Your username or password combination is incorrect</p>';
}
}
else
{
$error_msg= 'You must enter a username and password to log in';
}
}
}
$page_title='Log In';
require_once('header.php');
if(empty($_session['user_id']))
{
echo '<p class="error">'.$error_msg.'</p>';
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="username">Username:</label>
<input type="text" id="username" name="username" /><br/>
<label for="password">Password:</label>
<input type="password" id="password" name="password" /><br/>
<input type="submit" value="Log in" name="submit" />
</form>
<?php
}
else {
// Confirm the successful log-in
echo '<p class="login">You are logged in as ' . $_SESSION['username'] . '.</p>';
}
?>
I want to make my index.php accessible only after login
I have added this code to my index.php page
here is my index page:index.php
<?php
session_start();
if(!isset($_SESSION['user_id']))
{
echo '<p>Please Login to continue Log In</p>';
exit();
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="index_style.css" />
</head>
<script src="dropdown.js">
</script>
</head>
</html>
but even after logging in I'm again asked to log in.

I think your issue is that you're not setting $_SESSION['user_id'] properly
$row=mysqli_fetch_array($data);
$_SESSION['user_id']=$_row['user_id'];
Should be
$row=mysqli_fetch_array($data);
$_SESSION['user_id']=$row['user_id'];
Note that $_row became $row

Firstly, $_session that's a superglobal. It must be in uppercase.
http://php.net/manual/en/language.variables.superglobals.php
Then, you're using $_row but fetching the array using $row=mysqli_fetch_array($data);
so that will fail.
Use $_row=mysqli_fetch_array($data); if you want to keep what you've already coded.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
and or die(mysqli_error($dbc)) to mysqli_query() which would have caught the syntax error.
Sidenote: Error reporting should only be done in staging, and never production.

Related

PHP Multi-user Login with Session

I have 7 user levels. I will be redirected depending on my input (for example I input the credentials of the admin, i will be redirected to admin page) and same goes with the other 6. The problem I have is that after successfully logging in, if I change the url from (localhost/admin/home.php) to (localhost/employee/home.php) I can now access the employee's page. I want to have restrictions on that. Or maybe an error that says "Unauthorized user. Access denied." something like that. Here's my code.
index.php
<form action="checklog.php" method="POST">
<h1>Log in</h1>
<p>
<label for="username" class="uname" > Your email or username </label>
<input id="username" name="username" required="required" type="text" placeholder="myusername " minlength="2" />
</p>
<p>
<label for="password" class="youpasswd"> Your password </label>
<input id="password" name="password" required="required" type="password" placeholder="eg. X8df!90EO" minlength="2" />
</p>
<input type="submit" name="submit" value="Login">
</form>
<?php // To display Error messages
if(isset($_GET['err'])){
if ($_GET['err']==1){
echo "Invalid Credentials.";}
else if($_GET['err']==5){
echo "Successfully Logged out";}
else if ($_GET['err']==2){
echo "You're trying to access an unauthorized page.";
}
}
?>
</body>
checklog.php (This is where I process the credentials.)
<?php
require_once("db.php");
function check_input($r){
$r=trim($r);
$r=strip_tags($r);
$r=stripslashes($r);
$r=htmlentities($r);
$r=mysql_real_escape_string($r);
return $r;
}
if (isset($_POST['username'],$_POST['password'])){
$u=check_input($_POST['username']);
$p=md5(check_input($_POST['password']));
try{
$db=get_db();
$stmt=$db->prepare("SELECT * FROM users WHERE username=? && password=?");
$stmt->execute(array($u,$p));
$r=$stmt->fetch(PDO::FETCH_ASSOC);
if($r){
session_start();
$access_level=$r['access_level'];
$_SESSION['username']=$r['username'];
$_SESSION['access_level']=$access_level;
if ($access_level==0){
header("Location: admin/home.php");
}
if($access_level==1){
header("Location: user/home.php");
}
if($access_level==2){
header("Location: businesshead/home.php");
}
if($access_level==3){
header("Location: scm/home.php");
}
if($access_level==4){
header("Location: finance/home.php");
}
if($access_level==5){
header("Location: gm/home.php");
}
if($access_level==6){
header("Location: scma/home.php");
}
}
else{
header("Location:index.php?err=1");
}
}
catch(PDOException $e){
die("Database error: ".$e->getMessage());
}
}
else{
header("Location:index.php");
}
?>
And lets just assume that this is my admin page (admin.php)
<!DOCTYPE html>
<body>
Welcome!
</body>
</html>
Thank you in advance!
You have to check session on every page. Put related code on top of every page like
admin page
<?php
session_start();
if($_SESSION['type'] != 0){
echo "Unauthorized user. Access denied."
die; // stop further execution
} ?>
user page
<?php
session_start();
if($_SESSION['type'] != 1){
echo "Unauthorized user. Access denied."
die; // stop further execution
} ?>
use this one code in top of the all pages
<?php if($_SESSION['type']==1){
header('index.php?msg=Admin Not Access This page');
}?>

My login page keeps returning "incorrect login" even when I enter correct login

I wrote a simple login page that is connected to a mySQL database. But even when I try to put in the correct login information, it still returns the "Incorrect username or password" error. I can't figure out if there is something wrong with my code itself, or my database. Any help would be greatly appreciated!
My database looks like this: https://gyazo.com/da06e276d981a35a3e2f01f5ec17f27b
I currently have 2 entries in that database for testing: https://gyazo.com/04a52dde61e77e0cbc2f90b78b3f40a9
My index.php code is as follows
<?php
include('login.php'); // Include Login Script
if ((isset($_SESSION['username']) != ''))
{
header('Location: home.php');
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Login Form with Session</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1>PHP Login Form with Session</h1>
<div class="loginBox">
<h3>Login Form</h3>
<br><br>
<form method="post" action="">
<label>Username:</label><br>
<input type="text" name="username" placeholder="username" /><br><br>
<label>Password:</label><br>
<input type="password" name="password" placeholder="password" /> <br><br>
<input type="submit" name="submit" value="Login" />
</form>
<div class="error"><?php echo $error;?></div>
</div>
</body>
</html>
My login.php code is as follows:
<?php
session_start();
include("connection.php"); //Establishing connection with our database
$error = ""; //Variable for storing our errors.
if(isset($_POST["submit"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$error = "Both fields are required.";
}else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
//Check username and password from database
$sql="SELECT uid FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
//If username and password exist in our database then create a session.
//Otherwise echo error.
if(mysqli_num_rows($result) == 1)
{
$_SESSION['username'] = $login_user; // Initializing Session
header("location: home.php"); // Redirecting To Other Page
}else
{
$error = "Incorrect username or password.";
}
}
}
?>
1- Saving in plain text is a NO.
2- As far as i can see you are comparing a plain text password with its md5.
You have also defined the same variable more than once, with different values, sth ive never seen before.
Well, I don't see where $login_user is assigned a value in your code in login.php page.
Try
$_SESSION['username'] = $username;
Also replace this with what you have at the top of your index.php page.
<?php
include('login.php'); // Include Login Script
if (isset($_SESSION['username'])){
header('Location: home.php');
}
else{}
?>
First of since you have your login script on another file in your project directory, shouldn't you specify the location to the script on your login form? Just like this
<form method="post" action="login.php">
<label>Username:</label><br>
<input type="text" name="username" placeholder="username" /><br><br>
<label>Password:</label><br>
<input type="password" name="password" placeholder="password" /> <br><br>
<input type="submit" name="submit" value="Login" />
</form>

Why i cannot display the error message in the login page?

i want to display my error message in the login form by getting the result from the login.php ,here is the sample code that i have use.The first part is the index.php
<?
include("login.php");?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<h1>Hup Seng</h1>
<div id="login">
<h2>Login Form</h2>
<form action="login.php" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text" required>
<br>
<br>
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password" required>
<br>
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
</body>
</html>
Here is the login.php i have put the error message under the else statement in order to pass the information to the login form
<?php
include("dbconfig.php");
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
//if (isset($_POST['submit'])) {
if (isset($_POST['username']) || isset($_POST['password'])) {
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
$pw = encode($password);
$sql = "SELECT count(ID) as cid FROM tblUser WHERE UserId = '$username' and Password1 = '$pw'";
$rs = odbc_exec($link_mssql,$sql);
while (odbc_fetch_row($rs)) {
$count=odbc_result($rs,"cid");
}
if ($count == 1) {
$_SESSION['username']=$username; // Initializing Session
header("location: homepage.php"); // Redirecting To Other Page
} else {
$error="username/passwod combination incorrect";
header("location: index.php");
}
odbc_close($link_mssql); // Closing Connection
}
//}
?>
No need to add header you already including login.php file in index.php
$error="username/passwod combination incorrect";
//header("location: index.php");//remove this line
session_start();
$_SESSION['error']="username/passwod combination incorrect";
and in login form check
session_start();
if(isset($_SESSION['error'])){
echo $_SESSION['error'];
}
//header("location: index.php");
Remove this or you can redirect the page after some time if you want like this.
header( "refresh:5;url=index.php" ); // page redirect after 5sec

Redirecting to other PHP page

I have tried all methods but still am not seeing a redirect to index.php as expected.
I also added ob_start() but it doesn't work. Then I tried header('location:...'). It also didn't work. Then I tried to redirect using JavaScript but that also didn't work.
Any suggestions ??
<html>
<head>
<link rel ="stylesheet" href=css/style.css>
</head>
<body>
<?php
ob_start();
require('dbconnect.php');
require('loginservice.php');
session_start();
//if my form is submitted
if(isset($_POST['submit']))
{
$username=$_POST['username'];
$password=$_POST['password'];
$query1= userIdentity($username,$password);
echo 'returning value deisplay';
echo '\n' .$query1 . '\n';
echo 'i am here';
if($query1==1){
//echo 'welcome dude';
$_SESSION['username'] = $username;
// Redirect user to index.php
//echo "<script type='text/javascript'> window.location='index.php'; </script>";
// header("Location: index.php");
//e//cho 'heeeelo';
echo "<script type='text/javascript'>window.location.href = 'index.php'; </script>";
ob_flush();
exit(0);
}
// header("Location: index.php");
else
{
echo " <div class='form'>
<h3>Username/password is incorrent.</h3>
<br/>click here to <a href='login.php'>Login</a></div>";
}
//header("Location: index.php");
}
else {
?>
<div class="form">
<h1>Log In</h1>
<form action="" method='post' name="login">
<input type ="text" name="username" placeholder="username" required />
<input type="password" name="password" placeholder="password" required />
<input name="submit" type="submit" value="login" />
</form>
<p> Not registered yet ? <a href='register.php'>Register Here </a> </p>
</div>
<?php
}
?>
</body>
</html>
Per the PHP manual page for header():
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
So move the PHP code above the starting HTML tags, like the example below. I created a variable to hold the message in case the login attempt fails (i.e. $message). Notice how it is set it to a blank message initially (for good scope) and then set when appropriate. Then it is added to the form down below.
Edit:
You can see this demonstrated in this phpFiddle. Try logging in with any username. If you enter the password pw, then you should be taken to index.php, which on that page display an image with the text phpfiddle.org. Also, I removed the HTML from the else block, so it will always show the form (and insert the login failure message if it is set), though you might want to have it not show the form again if the login fails...
<?php
ob_start();
require('dbconnect.php');
require('loginservice.php');
session_start();
$message = ''; //initialize to empty, for good scope
//if my form is submitted
if(isset($_POST['submit']))
{
$username=$_POST['username'];
$password=$_POST['password'];
$query1= userIdentity($username,$password);
if($query1==1){
$_SESSION['username'] = $username;
// Redirect user to index.php</script>";
header("Location: index.php");
//...
}//else:
else {
$message = "<div class='form'><h3>Username/password is incorrect.</h3>
<br />click here to <a href='login.php'>Login</a></div>";
}
?>
<html>
<head>
<!-- the rest of the HTML content -->
and in the body, append that incorrect message if it is defined, e.g.:
<div class="form"><?php echo $message; ?>
<h1>Log In</h1><!-- rest of the HTML for the form-->
Instead of having the html <html><head><body> tags before your php code, have the php code before these and use the header function. Here is the working new version:
<?php
ob_start();
require('dbconnect.php');
require('loginservice.php');
session_start();
//if my form is submitted
if(isset($_POST['submit']))
{
$username=$_POST['username'];
$password=$_POST['password'];
$query1= userIdentity($username,$password);
echo 'returning value deisplay';
echo '\n' .$query1 . '\n';
echo 'i am here';
if($query1==1){
//echo 'welcome dude';
$_SESSION['username'] = $username;
// Redirect user to index.php
//echo "<script type='text/javascript'> window.location='index.php'; </script>";
// header("Location: index.php");
//e//cho 'heeeelo';
header("Location: index.php);
ob_flush();
exit(0);
}
// header("Location: index.php");
else
{
echo " <div class='form'>
<h3>Username/password is incorrent.</h3>
<br/>click here to <a href='login.php'>Login</a></div>";
}
//header("Location: index.php");
}
else {
?>
<html>
<head>
<link rel ="stylesheet" href=css/style.css>
</head>
<body>
<div class="form">
<h1>Log In</h1>
<form action="" method='post' name="login">
<input type ="text" name="username" placeholder="username" required />
<input type="password" name="password" placeholder="password" required />
<input name="submit" type="submit" value="login" />
</form>
<p> Not registered yet ? <a href='register.php'>Register Here </a> </p>
</div>
<?php
}
?>
</body>
</html>

i am trying to practice a simple session code in my house in xamp

but some how the page is not showing any error message. also it is not redirecting to the page where i want to redirect it after successful login. i want the login page to be redirected at home page and show the message and when the logout link is clicked the page again come back to the login page
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
?>
<?php
if($_REQUEST["logout"]=='yes'){
unset($_SESSION["login"]);
}
?>
<html>
<body>
<form action="" method="post">
<label>Username</label><input type="text" name="unametxt" value="<?php echo $_post["unametxt"]; ?>" />
<label>Password</label><input type="password" value="<?php echo $_post["password"]; ?>" />
<input type="submit" name="sbt" value="Login">
</form>
<?php
if(isset($_post["sbt"]))
{
if($_post["unametxt"]== "debarun" && $_post["password"]=="1234")
{
$_SESSION["login"]="yes";
$_SESSION["uname"]=$_post["unametxt"];
$_SESSION["passwd"]=$_post["password"];
header('location:home.php');
}
else
{
echo "Please enter correct credentials";
}
}
?>
</body>
</html>
and it is my home page script:
<?php
session_start();
if(!isset($_SESSION["login"])){
session_destroy();
header('location:login.php');
}
else{
echo "Welcome".$_SESSION["uname"]."<br/>"."your password is".$_SESSION["passwd"];
}
?>
<html>
<body>
<form action="" method="post">
Logout
</form>
</body>
</html>
please
tell me why it is not working??
Add name attribute in your password element. Because of this, it cannot fetch from $_POST array and your condition will always fail.
Try this,
<label>Password</label><input type="password" name="password" value="<?php echo $_post["password"]; ?>" />
First thing $_post must be up letter case like this $_POST then you forgot to specify name="password" to password input field
take a look
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
?>
<?php
if($_REQUEST["logout"]=='yes'){
unset($_SESSION["login"]);
}
?>
<html>
<body>
<form action="" method="post">
<label>Username</label><input type="text" name="unametxt" value="<?php echo $_POST["unametxt"]; ?>" />
<label>Password</label><input type="password" name="password" value="<?php echo $_POST["password"]; ?>" />
<input type="submit" name="sbt" value="Login">
</form>
<?php
if(isset($_POST["sbt"]))
{
echo $_POST["password"];
if($_POST["unametxt"] == "debarun" and $_POST["password"] == "1234")
{
$_SESSION["login"]="yes";
$_SESSION["uname"]=$_POST["unametxt"];
$_SESSION["passwd"]=$_POST["password"];
header('location:home.php');
}
else
{
echo "Please enter correct credentials";
}
}
?>
</body>
</html>
Put all those validation code at the top. Nothing should be sent to the browser before redirecting. Not even an empty line.
Also, make the L in location capital
header("Location: home.php");

Categories