PHP Session forms - php

I'm having some difficulty with PHP sessions.
The idea is to prevent users from accessing the administrator panel / pages by using the direct URL.
I have created a login form and that works well (login.php)
Once the username and password are correctly entered, the login form takes the user to the admin panel (admin.php)
However when I added the following script PHP to the (admin.php) page, it does not work.
When I enter the username and password on the login page, it always fails and re-directs me to login.php
The script on the admin.php is used to prevent users from accessing the page if
the session variable is not set
ANY help greatly appreciated :)
<link rel="stylesheet" type="text/css" href="admin_panel.css" media="all">
</head>
<body>
<form method="post">
<input type="text" name="user_name" placeholder="Username" required="required" />
<input type="password" name="user_pass" placeholder="Password" required="required" />
<button type="submit" class="btn btn-primary btn-block btn-large" name="login">Let me in.</button>
</form>
</div>
</body>
//===================================== login.php
<?php
include("includes.php");
if(isset($_POST['login'])) {
echo $user_name = mysql_real_escape_string ($_POST['user_name']);
echo $user_pass = mysql_real_escape_string ($_POST['user_pass']);
$encrypt = md5($user_pass);
$select_user = "select * from users where user_name= '$user_name' AND user_password = '$user_pass'";
$run_user = mysql_query($select_user);
if(mysql_num_rows($run_user)>0){ // what does this function DO?
$_SESSISON['user_name'] =$user_name;
echo "<script> window.open('admin_panel.php?logged=You have logged in','_self' )</script>";
}
else {
echo "<script> alert('Wrong details')</script>";
} }
?>
</html
// admin.php script ====================
<?php
session_start();
if(!isset($_SESSION['user_name'])) {
echo "<script>window.open('login.php','_self')</script>";
}
else { // ELSE CLOSED BOTTOM OF THE PAGE
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin page</title>
<link rel="stylesheet" type="text/css" href="admin_panel.css" media="all">
</head>
<body>
comments(0)
Insert New Post
Admin Logout
<?php
if(isset($_GET['insert_cat'])) {
include("insert_cat.php");
}
if(isset($_GET['insert_post'])) {
include("insert_post.php");
}
?>
</body>
<?php } ?> // CLOSE ELSE
</html>

It's better to use an authentication system from framework like Zend, Symfony, Laravel etc. than $_SESSION included in PHP.
To redirect user you can use function header()
for example:
header('Location: login.php');
it's important to set charset to 'UTF-8 without BOM' and it can't be any output before header()

Related

Simple login without encryption in PHP

I'm making a very simple login script (beginner at PHP) and here is my code. I can't figure out how to redirect after true login credentials. I know this probably is a duplicate but I can't figure this out without help on my exact script (as mentioned above I'm not that good).
update: So I have fixed name in password, form method, and the redirect . But now I'm getting to a empty page, something is wrong with my function as one comment earlier. I'm also a dummie at MySQL can someone help me further? My code is updated
Another update
Okay so i have finished all of my script, but the problem is my sql functions. So does anyone know mysqli and can translate it?
<?php $tilkobling = mysqli_connect("localhost","root","root","login_form");
if(isset($_POST["name"], $_POST["password"]))
{
$name = $_POST["name"];
$password = $_POST["password"];
$result1 = mysql_query("SELECT username, password
FROM user
WHERE username = '".$name."'
AND password = '".$password."'");
if(mysql_num_rows($result1) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $name;
header("Location: information_site.php");
}
else
{
echo 'The username or password are incorrect!';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>login</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h2>bypass to information site</h2>
<div class="login-page">
<div class="form">
<h1>Login</h1>
<form method="post" class="login-form">
<input name="name" type="text" placeholder="username"/>
<input name="password" type="password" placeholder="password"/>
<button name="submit">login</button>
<p class="message">Not registered? Create an account</p>
</form>
</div>
</div>
<script type="text/javascript">
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
</script>
</body>
</html>
You're using mysqli connector and mysql functions so let's assume you'll use mysql for all
$tilkobling = mysql_connect("localhost","root","root");
mysql_select_db( "login_form", $tilkobling );
and you'll need to add session_start() before using/setting any session variables
session_start();
$_SESSION["logged_in"] = true;
Your header needs to be in the true portion of the if/else, which is where you set your $_SESSION variables, here you are:
if(mysql_num_rows($result1) > 0 )
{
session_start();
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $name;
header("Location: information_site.php");
}
Have you Tried the HTML meta tag, this subtitutes the header() function.
Of course initially convert it into PHP code. Like this:
Echo "<meta http-equiv='refresh' content='0; URL=put your url in here to the page you like to redirect to'>" ;
This should probably operate correctly.

How can ask login if it write on url

index.php
<?php session_start(); ?>
<?php include('dbcon.php'); ?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="form-wrapper">
<form action="#" method="post">
<h3>Login here</h3>
<div class="form-item">
<input type="text" name="user" required="required" placeholder="Username" autofocus required></input>
</div>
<div class="form-item">
<input type="password" name="pass" required="required" placeholder="Password" required></input>
</div>
<div class="button-panel">
<input type="submit" class="button" title="Log In" name="login" value="Login"></input>
</div>
</form>
<?php
if (isset($_POST['login']))
{
$username = mysqli_real_escape_string($con, $_POST['user']);
$password = mysqli_real_escape_string($con, $_POST['pass']);
$query = mysqli_query($con, "SELECT * FROM users WHERE password='$password' and username='$username'");
$row = mysqli_fetch_array($query);
$num_row = mysqli_num_rows($query);
if ($num_row > 0)
{
$_SESSION['user_id']=$row['user_id'];
header('location:home.php');
}
else
{
echo 'Invalid Username and Password Combination';
}
}
?>
</div>
</body>
</html>
Here is my page for login the system. When the username and password is then it will go to home pages. It work properly. but if I write in browser after log out.
localhost/logg/home.php it is automatically go to that pages it not asking for login. So How to make proper login page where it asking log or automatically it will go login panned for all the pages is that is connected with home page.
home.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Client Management System</title>
<link rel="stylesheet" type="text/css" href="css/style_entry.css" />
<link rel="stylesheet" type="text/css" href="css/home_menu.css" />
<link rel="stylesheet" type="text/css" href="css/container.css" />
</head>
<body style="background-color:gray"/>
<div class="container">
<div class="dropdown">
<button class="dropbtn">Entry</button>
<div class="dropdown-content">
Market Information
bank Information
Client Information
</div>
</div>
Edit
Bill Process
Bill Print
Bill Posting
Report
Admin
Help
Help
<li style="float:right"><a class="active" href="logout.php">Logout</a></li>
</body>
logout.php
<?php
session_start();
session_destroy();
header('location:index.php');
?>
How can I secure it ?? how can I set if I write the url in browser then it will automatically go to the login page.
1st : On top of every page you need to check session is exists or not . if session exists allow user to see the page otherwise redirect the page to login page .
if(!isset($_SESSION['user_id'])){
header('Location:login.php');
exit();
}
Note : Session is globally accessible variable . Based on that you need to make logic .
make a file 'login_check.php'
<?php
if(isset($_SESSION['user_id'])){
}else{
header("location:login.php");
}
?>
include this file in those pages which should only be accessible to logged in user.

force login page before index

I have a login form that displays a message when a user either registers or logins in. I would like the login page to open first and after successful login then index.php can be shown. also should someone try and access /index.php directly it must still direct them to login.php to be authenticated. I have tried some examples of other peoples codes but i cannot get the page to authenticate the user.
My Login.php code:
<?php
session_start();
require_once('connect.php');
if(isset($_POST) & !empty($_POST)){
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = md5($_POST['password']);
$sql = "SELECT * FROM `login` WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $sql);
$count = mysqli_num_rows($result);
if($count == 1){
$_SESSION['username'] = $username;
}else{
$fmsg = "Invalid Username/Password";
}
}
if(isset($_SESSION['username'])){
$smsg = "User already logged in";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>User Login in PHP & MySQL</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="container">
<?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?>
<?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?>
<form class="form-signin" method="POST">
<h2 class="form-signin-heading">Please Register</h2>
<div class="input-group">
<input type="text" name="username" class="form-control" placeholder="Username" required>
</div>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholde r="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
<a class="btn btn-lg btn-primary btn-block" href="register.php">Register</a>
</form>
</div>
</body>
</html>
You can if statement to check whether user is login or not.
If user is not logged in then you can redirect them to login.php
If user is logged in then you can let them see index page.
To do so, code example is given below....
<?php
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
$welcomeMessage = "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
header('Location: login.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Index page</title>
</head>
<body>
<?
if(!empty($welcomeMessage)) echo $welcomeMessage;
?>
Index page
</body>
</html>
I would like the login page to open first and after successful login then index.php can be shown.
Well you could create a .htaccess file then add this line:
DirectoryIndex login.php when someone visits your site will go to login.php
then on login.php
first check if that user is not loggedin already
therefore login.php
<?php
session_start();
require_once('connect.php');
if(isset($_SESSION['username'])){
$smsg = "User already logged in";
header("location:index.php"); // send to index if logged in
}else{
// the code you have in your question here
}
?>
also should someone try and access /index.php directly it must still direct them to login.php to be authenticated. You would need to check if the session is set or not if its set continue or send them back to login
index.php
<?php
session_start();
if(isset($_SESSION['username'])):?>
Your html content
<?php
else:
header("location:login.php");//send them to login
endif;
?>
The absolute easiest way (according to me) would be to create a new file called auth.php with the following content:
<?php
session_start();
if (empty($_SESSION['username'])) {
// The username session key does not exist or it's empty.
header('location: /login.php');
exit;
}
Then, in the very top of every page you want to protect (including your index.php), just add:
<?php
require __DIR__ . '/auth.php';
?>
// Continue with your HTML here
No need to build the sites inside if/else-statements.
Note: This assumes that all your pages are in the root folder. If you have other pages in sub folders that you want to protect, you need to add the correct path to auth.php, since __DIR__ gives you the absolute path of the file you write it in.

Prevent opening page without login

I have created a webpage (lets call the root as main.php) and decided to put a login on top of it (file index.php). The login works fine, but the problem is this. If I type the address of the page (main.php) directly in the browser, it is opened.
Is there any way to prevent opening the page unless I go through the login?
In case it is relevant, this is the login code:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<div class="login_container">
<div id="login-form">
<h3>Login</h3>
<fieldset>
<form action="checklogin.php" method="post">
<input name="username" type="text" required placeholder="Username">
<input name="password" type="password" required placeholder="*******">
<input type="submit" value="Login">
</form>
</fieldset>
</div>
</div>
</body>
</html>
and it directs to :
<?php
ob_start();
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$username = pg_escape_string($username);
$password = pg_escape_string($password);
if($username == "username" && $password == "password"){
$_SESSION['username']="username";
$_SESSION['password']="password";
header("location:main.php");
}
else header("location:index.php");
ob_end_flush();
?>
You need to check, on every request that requires a login, that the user is logged in and is authorized.
A good way of looking at this is seeing the request URL as part of the input to your program. Just like the cookies and GET/POST parameters are input.
main.php will either return a page with data or a request for login.
Sure.
Check if the user is currently logged on when they access the page using php sessions if they aren't logged on send an error, or redirect them elsewhere.

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>

Categories