I have created some pages using html and php. In home page I have links of all pages. Now I want to add authentication to each page. The page should not get open without the authentication.
For this I have created one login page which will check authentication.
Now from home page I want to open the login page if any page's link is clicked, and if the login is successful I want to open the page which link is clicked.
Home Page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Questions</title>
</head>
<body>
Add a chapter<br><br>
Upload a file<br><br>
Upload a video<br><br>
Add a question<br><br>
Delete chapters<br><br>
Delete Files<br><br>
Delete video Files<br><br>
Delete questions
</body>
</html>
Login page:
<!DOCTYPE html>
<html>
<head>
<body>
<form action="Login.php" method="post" enctype="multipart/form-data">
Enter Username : <input name = "userName" type = "text"><br><br>
Enter Password : <input name = "pass" type = "text"><br><br>
<input name="submit" type="submit" value = "Submit"><br><br>
<?php
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
$dbh = new PDO('mysql:host=174.138.74;dbname=_pro','rpro', 'ro12345');
if(isset($_POST['submit'])) {
if (!empty($_POST['userName']) && !empty($_POST['pass'])) {
$stmt = $dbh->prepare("select * FROM `users` WHERE `username`= :uName and `pass` = :pass");
$stmt->bindParam("uName", $_POST['userName']);
$stmt->bindParam("pass", $_POST['pass']);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if ($count > 0) {
echo 'Login Successful.';
?>
<?php
} else {
echo 'Please enter correct username and password.';
}
}
else{
echo 'Please enter username and password.';
}
}
?>
</form>
</body>
</head>
</html>
How can I achieve this? Please help. Thank you..
You can make your all links like these...
Add a chapter<br><br>
Upload a file<br><br>
Upload a video<br><br>
Add a question<br><br>
Delete chapters<br><br>
Delete Files<br><br>
Delete video Files<br><br>
Delete questions
Then when user will click on any link, it'll redirect them to login.php page. At there make all kind of validation of user credentials & if validation is found out as TRUE then get redirect part of URL from the previous link & reconstruct the destination page once again by
$destination_page = $_GET['redirect'];
& redirect the user to that page else ask the user for login again.
You can authenticate using sessions as:
After successfully logged in, create $_SESSION[]
Create common file where you can check is session set
if session is not set then you can redirect to login page
include this file in all pages
Set a session variable. Note that you should put headers at the top, before any output.
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
$dbh = new PDO('mysql:host=174.138.74;dbname=_pro','rpro', 'ro12345');
if(isset($_POST['submit'])) {
if (!empty($_POST['userName']) && !empty($_POST['pass'])) {
$stmt = $dbh->prepare("select * FROM `users` WHERE `username`= :uName and `pass` = :pass");
$stmt->bindParam("uName", $_POST['userName']);
$stmt->bindParam("pass", $_POST['pass']);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if ($count > 0) {
$_SESSION['authenticated_user'] = $_POST['userName'];
header("Location: http://www.example.com/loginsuccess.php");
?>
<?php
} else {
echo 'Please enter correct username and password.';
}
}
else{
echo 'Please enter username and password.';
}
}else{
?><!DOCTYPE html>
<html>
<head>
<body>
<form action="Login.php" method="post" enctype="multipart/form-data">
Enter Username : <input name = "userName" type = "text"><br><br>
Enter Password : <input name = "pass" type = "text"><br><br>
<input name="submit" type="submit" value = "Submit"><br><br>
</form>
</body>
</head>
</html>
<?php
}
?>
Now on the other pages check if they are authenticated by checking the session.
<?php
if (!isset($_SESSION['authenticated_user'])){
header("Location: http://www.example.com/noaccess.php");
}
?>
Related
I am creating a simple login and logout for my homework, I am using $_SESSION to show the username from database of the currently logged in user. Login and logout is working but when back button of the browser is pressed it will go back to my previous page where I logged out. Because it was already session_destroy when I logged out it would output an error as back button was pressed.
Tried disabling the back button but doesn't look good, user might think webpage is broken
samp.php
<?php
session_start();
if(isset($_POST['botLogin']))
{
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'db_name';
$conn = new mysqli($host, $user, $pass, $db);
$username = $_POST['username'];
$password = $_POST['password'];
$result = $conn->query("SELECT * FROM tbl_name WHERE col_userName = '$username' AND col_custPass = '$password' ");
if(mysqli_num_rows($result)==1)
{
$_SESSION['session_var_user'] = $username;
header('Location:samp2.php');
}
else
{
echo "Username or password mismatch";
}
}
?>
<form action = "samp.php" method="post">
<input type = "text" name = "username" placeholder="username">
<input type = "text" name = "password" placeholder="password">
<input type = "submit" name = "botLogin" value = "login">
</form>
samp2.php
<?php
session_start();
echo "Hi," . $_SESSION['session_var_user'];
if(isset($_POST['logout']))
{
session_destroy();
echo "<script>location.href='samp.php';</script>";
}
?>
<form action = "samp2.php" method="post">
<input type="submit" name="logout" value="logout">
</form>
If I logged out is it possible when back button is pressed it will just direct me to login page again instead of directing me to previous page?
error when back button button is pressed after logging out:
Notice: Undefined index: session_var_user in C:\xampp\htdocs\name\samp2.php on line 4
Hi,
The solution is simple, in samp2.php replace the 'session_start();' with the below code
if (session_status() == PHP_SESSION_NONE) {
session_start(); }
if (isset($_SESSION['session_var_user'])) { }
else {
header("Location: /samp.php/"); }
This code will check if the session does exist, if it does not, it will redirect the user to the login page
Thanks for answering mr. cg . I just created a different login page without navbar and even I pressed the back button it won't show the error undefined index and it will just return to login page.
process of loggin it
if($row['col_userName'] == $username AND $row['col_custPass'] = $password){
$_SESSION['session_var_user'] = $username; // I created the session variable
echo "
<script>
window.location.href = 'index.php';
</script>
";
}else{echo "failed";}
code in navbar
<li class="nav-item">
<a class = "justtextstyle" href="#">
<?php
if(!isset($_SESSION['session_variable']))
{
echo "<a class = 'justtextstyle' href='login.php'>Log In Here</a>";
}
else
{
echo "Hi," . $_SESSION['session_variable'];
}
?>
</a>
</li>
the code in my question is different but same idea because that was the experimental php file and this was my actual assignment. I always make experimental file first coz i don't wanna mess with the original file lol.
or try to put this in navbar, indicating that if the session is not set it will redirect to index because session will only be set after successful login and if you logout the session would unset even if you press back button it will not go back to your previous page because session is still unset.
I'm trying to create a simple login promt on my local website. I already tried with Javascript, but I don't want the password to be hardcoded. The Users get the password by mail so there is no registration form needed. I searched on the Internet and I think it should work with PHP and Javascript. This is what i've come up with:
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Enter password',' ');
while (testV < 3) {
if (!pass1)
window.open('Website.html',"_self");
if (pass1.toLowerCase() == "password") {
alert('Correct!');
window.open('./test/sitetwo.html',"_self");
break;
}
testV+=1;
var pass1 =
prompt('Wrong Password','Try again');
}
if (pass1.toLowerCase()!="password" & testV ==3)
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Protected Area" onClick="passWord()">
</FORM>
</CENTER>
Does anyone of you know how to code this? Thank you for your help.
Login prompt is just one of possible approaches to hide information on your website. You have to decide first what are you trying to hide. For instance, if you if are providing some paid information to your clients - you can send the information itself by mail (instead of password). If you want to hide some part of site from other people - you can just give it weird url, like site.com/jkhgdsdkgf
Creating login backend with php and database obviously requires your php, mysql (or other database) and server administration skills and completely depends on details of your task, so it's hard to provide a useful advice here.
In my opinion, you should use a database to store all your credentials (like username, password, etc..)
If you don't know how to do it, you should know that if you want to run your php code, you need a php server and somewhere to put your db.
Here is how to set up a php server with Apache
https://www.ultraedit.com/support/tutorials-power-tips/uestudio/local-php-mysql-dev-environment.html
Here is how to set up a db with PhpMyAdmin
https://www.siteground.com/tutorials/phpmyadmin/create-populate-tables/
You need a login.php (where you log in), a test.php page (then you put in it whatever you want) and a check_User.php page (where to control if the credentials are correct).
Login.php
<html>
<head> <title>Login</title> </head>
<body>
<form action="check_User.php" method="post" id="login_form">
<label><b>Username</b></label>
<!-- USERNAME -->
<input type="text" placeholder="Enter Username" name="username" required>
<!-- PASSWORD -->
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<!-- LOGIN -->
<button type="submit">Login</button>
</form>
<body>
</html>
check_User.php
<?php
session_start();
$_POST["username"] = htmlspecialchars($_POST["username"]);
$_POST["password"] = htmlspecialchars($_POST["password"]);
$link = mysqli_connect("your_host", "your_db_username", "your_db_password", "your_db_name");
$query = "SELECT username, password
FROM your_db_name
WHERE username = \"".$_POST["username"]."\" AND password = \"".$_POST["password"]."\"
";
mysqli_query($link, $query);
$rows = array();
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
$rows[] = $row;
/* correct match */
if(mysqli_affected_rows($link) == 1)
{
$_SESSION["username"] = $_POST["username"];
$_SESSION["password"] = $_POST["password"];
}
if(isset($_SESSION["username"]) && isset( $_SESSION["password"]))
header("Location:test.php");
else {
alert("Wrong username or password");
}
?>
test.php
<?php
session_start();
// not logged in, not showing this page
if((!isset($_SESSION["username"]) || !isset( $_SESSION["password"]))
header("Location:login.php");
?>
<html>
....whatever you want this page to do
</html>
So I am using AJAX in a hybrid app to authenticate a user and also start a php session.
The app has public sections and a user account section. I wanted that when someone logs in they can go to the public sections and return to the user sections without being logged out.
So I wrote an AJAX request that is triggered when a user clicks the user section icon to check for sessions. If there is one then the js must load the user home page. If there is none the js must load the login page.
However when the user logs in and tries to return to the user home page the session checking script says the server says there is no session variable set. Below is the code.... First the login then the session checking code.
login.php
<?php
require("session.php");
header('Access-Control-Allow-Origin: *');
if($_SERVER['REQUEST_METHOD'] == "POST")
{
require("dbconnect.php");
$inv = sanity($_POST['inv']);
$acc = sanity($_POST['acc']);
$pass = sanity($_POST['pass']);
$query = "SELECT loginid FROM login WHERE institution_id = '$inv' AND username = $acc AND password = '$pass'";
$result = mysqli_query($db_conn, $query);
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
$_SESION['id'] = $row['loginid'];
echo "1";
}
else
echo "0";
}
function sanity($data)
{
$var = htmlspecialchars($data);
$var = trim($var);
return $var;
}
?>
confirm.php
<?php
require("session.php");
header('Access-Control-Allow-Origin: *');
if($_SERVER['REQUEST_METHOD'] == "GET")
{
if(isset($_SESSION['id']))
echo "1";
else
echo "0";
}
?>
the confirm script is returning zero though the login script returns 1
note that the session.php file does exist
This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 7 years ago.
I have a HTML5 app on my phone. When I input the correct username and password, it should go to an external server, log on to that database, check credentials and redirect me to another page(Home Page) on my phone when the credentials are correct.
I am able to reach the server and check credentials, but how do I redirect back to the Home Page which is in the app?
Did some reading and found ajax to be a viable option. But even then, am not entirely sure how to do the redirect. I have written the ajax section too and attached below. Please advice how I can adjust it to work.
First page on the app where you enter log in details:
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="scripts.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
</head>
<body>
<div data-role="page" id="loginForm">
<form id="form1" name="form1" method="POST" action="http://www.examplewebsite.com/login.php">
<input type="text" name="user" id="user" placeholder="Username"/>
<input type="password" name="pass" id="pass" placeholder="Password" />
<input type="submit" name="submit" value="Login" />
</form>
</div>
<div data-role="page" id="home">
<h1>Logged In</h1>
</div>
</body>
</html>
Script to check Log in. This php file rests on the server side.
//DB Log in credentials
$hostName = 'localhost';
$dbUser = 'fakeuser';
$dbPass = 'fakepass';
$dbName = 'fakedb';
$userTable = "faketable";
//Connect to DB
$conn = mysql_connect($hostName, $dbUser, $dbPass) or die("not connecting");
$dbSelect = mysql_select_db($dbName) or die("no db found");
//Obtain input username and password from the client
$username = $_POST["user"];
$password = $_POST["pass"];
//Check for MySql Injections
if(ctype_alnum($username) && ctype_alnum($password)){
$query1 = mysql_query("SELECT * FROM $userTable WHERE username='$username'");
//query will return 1 if the username exists in the database
$numrows = mysql_num_rows($query1);
if($numrows == 1){
//checking if the password matches the username now
$query2 = "SELECT password FROM $userTable WHERE username='$username'";
$result2 = mysql_query($query2);
$row = mysql_fetch_array($result2, MYSQL_ASSOC);
$pass = $row['password'];
if($password == $pass){
//If successful, redirect to the #home page
//anything I can do here to redirect back to #home on my app?
}
else
echo "Password incorrect";
}
else
echo "username incorrect" . $numrows;
}
else{
echo "Not alpha Numeric Input!!";
}
Attempted Ajax portion
var isLogged = false;
/**
* Method used to log into the application
*/
$(document).on("pageinit", "#loginForm", function () {
$("#form1").on("submit", function (event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "http://www.examplewebsite.com/login.php",
data: $("#form1").serialize(),
success: function (data) {
console.log(data);
if (data.loggedIn) {
isLogged = true;
$.mobile.changePage("#home");
} else {
alert("You entered the wrong username or password. Please try again.");
}
}
});
});
});
header("Location: thefile.php");
Replace thefile.php with your file to be redirected.!
You can use the "Location:" header or you can use the "META REFRESH" tag with an expiration of 0.
I am doing a web in where I want to prevent an user to access a content before he or she fulfill some predefined goal.
For example, I want to prevent an user to go to certain place of my page until they go to another place before. Like to prevent someone without the proper level to access that part of the web.
I want to avoid the use of password if possible.
I am going to use it in several parts of my webpage.
Thanks for your help.
You can use php session to do this. on your page that you want to restrict access to could have the following code:
<?php
session_start() // this starts the php session
if($_SESSION['auth'] !== 'true') // this checks if the session variable "auth"
// is not true
{
header("Location: /homepage.php"); // if "auth" is not true, it will redirect
// back to your home page. you can switch
// out "/homepage.html" with whatever your
// actual page is.
}
?>
<html>
<body>Rest of html content...
and the home page would look something like this:
<?php
session_start(); // starts the session
$buttonClicked=$_POST['access']; // checks to see if the button has been clicked
if($buttonClicked) {
$_SESSION['auth'] = 'true'; // sets the session variable auth to true so user
// can have access to other page
header("Location: /otherpage.php"); // sends the user to the other page
}
?>
<html>
<body>
<form method="post" action="homepage.php">
<input type="submit" value="Go to other page" name="access" />
</form>
</body>
</html>
When the user clicks the html button it will send them to the "otherpage.php" and they will be able to get in. both pages need to be .php not .html though.
Here is a quick example to your question:
index.php redirects the user to login.php if a specified $_SESSION variable does not exist.
login.php contains a basic account/password form. login.php use AJAX to call checkLogin.php to check whether the account/password are correct.
checkLogin.php checks whether the account/password are correct by comparing the user inputs with the data in database(mySQL in this example).
If the account/password are correct, checkLogin.php initiate $_SESSION["account"] and redirect the user back to index.php.
index.php
<?php
session_set_cookie_params(0);
session_start();
ob_start();
// Redirect to login.php if $_SESSION["account"] is not set
$url = "login.php";
if(isset($_SESSION["account"])!=true)
{
header('Location: '.$url);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<!-- Your secret contents here-->
<h1>Hello, your name is:</h1>
<?php echo $_SESSION["account"]; ?>
</body>
login.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function AjaxCheck()
{
if(document.getElementById("account").value==""){
document.getElementById("div_message").innerHTML = "You are not logged in.";
return;
};
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(xmlhttp.responseText.match("redirect")){
window.location.href = "index.php";
}
else{document.getElementById("div_message").innerHTML=xmlhttp.responseText;}
}
}
// Use HTTP get to send user input account/password to checkLogin.php
xmlhttp.open("GET","checkLogin.php?account="+document.getElementById("account"). value+"&password="+document.getElementById("password").value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<p>Account: </p>
<input type="text" name="account" id = "account"/>
<p>Password: </p>
<input type="password" name="password" id = "password" />
<br>
<a class="btn btn-primary" onClick = "AjaxCheck()">Login</a>
</form>
<div id = "div_message" >
div_message text
</div>
</body>
checkLogin.php
<?php
session_set_cookie_params(0);
session_start();
// NOTE: In real world, you should do some sanitization first
$account=$_GET["account"];
$password=$_GET["password"];
checkIfLogin();
function checkIfLogin(){
$con = mysql_connect("localhost","YourDatabaseAccount","YourDatabasePassword");
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_select_db("YourDB", $con);
$result = mysql_query("SELECT * FROM `YourTable` WHERE `Account` = '".$GLOBALS['account']."' " );
$row = mysql_fetch_array($result);
if($row==NULL){echo "This account does not exist"; mysql_close($con); return;}
if(strcmp($row['Password'],SHA1($GLOBALS['password']))==0){
$_SESSION['account'] = $GLOBALS['account'];
echo "redirect" ;
}
else{echo "Incorrect Password" ;}
mysql_close($con);
}
?>
Notes
The above example codes "work" but should be consider "dirty", just a quick example.
I know you want the answer as simple as possible, but an example with account/password should get you to know the feel how session or cookies work. You can implement the way you like later.
You may find these sites/topics useful:
AJAX
PHP 5 Sessions
PHP 5 Complete Form Example
PHP 5 Form Validation
basic SQL, and things about general Database and SQL.
P.S. Actually you don't need AJAX to achieve your goal, but why not learn more? :)
Edit: Just in case that you don't have a database available, here is a simple checkLogin.php which only allows user "John" with password "123" to pass.
<?php
session_set_cookie_params(0);
session_start();
$account=$_GET["account"];
$password=$_GET["password"];
checkIfLogin();
function checkIfLogin(){
if(strcmp($GLOBALS['account'],"John")!=0){
echo "Invalid Account";
}else if(strcmp($GLOBALS['password'],"123")!=0){
echo "Incorrect Password";
}
else{
$_SESSION['account'] = $GLOBALS['account'];
echo "redirect" ;
}
}
?>