How to secure page with access code - php

Okey guys , i try to secure page with access code ,but page is not secrued if some people write in url pagename.php page is loading without checked my code is. Code is work after put correct access code redirect to my page but , page is not secured client visit page without code after write in url my page .....
<?php
include ('modules/conf.php');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$secretcode = mysqli_real_escape_string($db,$_POST['secretcode']);
$sql = "SELECT * FROM password WHERE password = '$secretcode'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
if($count == 1) {
$_SESSION['login_user'] = $secretcode;
session_start();
header("location: question.php");
}else {
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("", "Съжеляваме вашият код е невалиден");';
echo '}, 1000);</script>';
}
}
?>
<div class="section">
<div class="container-fluid gamebox">
<div class="row">
<div class="col-md-6">
<div class="secretcode">
<h1 class="text-center">въведете код от брошурата</h1>
<form action="" method="post" class="formsecretcode text-center">
<input type="secretcode" id="codeverify" name="secretcode" placeholder="въведете вашият код">
<input type="submit" class="buttonsubmit" name="submit" value="провери код">
</form>
</div>
</div>

As I stated in comments and seeing that nobody posted an answer so far, am submitting the following.
Check to see if the session is set (with an optional "if { equal to something }"), and if not, else { kick them out }.
The logic is, and to be part of every page using sessions that you wish to protect and assuming $secretcode equals 12345 as an example:
<?php
session_start();
if (isset($_SESSION['login_user']) && $_SESSION['login_user'] == '12345'){
// Do something
}
else {
// Do something else
}
It's also best to add exit; after header, otherwise your code may want to continue executing.
Reference:
http://php.net/manual/en/function.header.php
Footnotes:
You don't need to use session_start(); twice as that may trigger that the session was already started.
Use it once and at the "top" of every page, while making sure you're not outputting before header.
References:
http://php.net/manual/en/features.sessions.php
How to fix "Headers already sent" error in PHP
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);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Additional notes:
You could optionally check for both a username and secret word in the query which makes it a bit more unique.
$username = "Johnny B. Good";
$sql = "SELECT * FROM password
WHERE username = '$username'
AND password = '$secretcode'";
Unless you're only checking for a secret code only, then leave your query the way it is now.

Related

getting data from a log in form checked,redirects into white page if i press refresh it goes to the pages it has to direct to

I am getting some information from the login page form.
When I press submit, it goes to a check-login.php page where there it checks from the database if the credentials are correct or wrong.
Then it redirects to a track page.
My problem is that when I press submit on the log in page with the correct credentials.
It redirects to a white page.
And then, if I press refresh, it redirects to the correct page.
<div>
<h1>Login Form</h1>
<form action="check-login.php">
<input type="text" name="user" placeholder="user">
<input type="password" name="password" placeholder="password">
<input type="submit" value="log in">
</form>
</div>
This is the check-login php page
<?php
session_start();
$user=$_GET['user'];
$pass=$_GET['password'];
include("dblogin.php");
$sql="SELECT * FROM login";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if($user==$row["username"] && $pass==$row["password"]){
$_SESSION["userid"]=$row["id"];
header ("Location: tracks.php");
}
}
if ($_SESSION["userid"]==""){
header ('Location: login.html?message=Wrong Username or Password');
}
?>
Try the following code to make a redirect:
http_response_code(302); // send redirect code
header('Location: /tracks.php'); // send Location header
exit(0); // don't send anything else
Try this,
If (!isset($_SESSION['userid'])
{
echo "script type='text/javascript'>window.location.href='login.html?message=Wrong Username or Password'/script";
}
There can be issue due to header function as sometime it doesn't work on some servers.
Note: complete script tag as I'm not able to add code from phone and script tags getting parsed.
I'm not sure this is the issue...
But even if it is not the fix, it can't be a bad thing to do.
Change your form tag like this:
<form action="check-login.php" method="post">
Then in you PHP change it to $_POST variables like this:
$user=$_POST['user'];
$pass=$_POST['password'];
And I strongly suggest again to ugrade your code from mysql to mysqli or prepared statements. There is plenty answers on SO about this.
EDIT
Previous changes I suggested are good.
But wasn't the issue.
An old memory came to me, as I already had a similar problem in the past.
The issue is that your $_SESSION["userid"]=$row["id"]; doesn't have the time to be written before the tracks.php gets accessed.
So do it like this:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if($user==$row["username"] && $pass==$row["password"]){
//$_SESSION["userid"]=$row["id"];
header ("Location: tracks.php?id=" . $row["id"]);
}
}
And in your tracks.php, set it to session.
$_SESSION["userid"]=$_REQUEST["id"];
$_REQUEST will catch $_POST and $_GET.
EDIT: Switch to mysqli
Try this... Even if it is not the fix we're after, it will be a good thing done.
You should apply this modification to all your PHP files.
I know mysql_query has security issues (but not exactly what)... And there may be performance issues too. So it's a good improvement to have at this point.
We'll then be sure the problem source isn't due to this.
<?php
session_start();
$user=$_REQUEST['user'];
$pass=$_REQUEST['password'];
//include("dblogin.php");
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_error()) {
echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
}
$sql="SELECT * FROM login";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$idFound=false;
while ($row = mysqli_fetch_array($result)) {
if($user==$row["username"] && $pass==$row["password"]){
//$_SESSION["userid"]=$row["id"];
$idFound=true;
$idFoundis = $row["id"];
break;
}
}
if ($idFound){
header ("Location: tracks.php?id=" . $idFoundis);
}else{
header ('Location: login.html?message=Wrong Username or Password');
}
?>

PHP: Setting the session information in a cookie won't be kept after page reloads?

I have a very simple php single page, that requires the user to insert a specific username and pass in order to access its contents.
It generates a cookie that allows the user to access that page for one day.
If the user is logged in, the list of contents appear. If it's not, it shows the form.
It is all inside a single index.php page.
This single "protected" page contains a form where the user can put some information and save it. After the user logs in, all the content is shown as intended. But when the user tries to submit that form and reloads the page (the new content should be added to that page), it gets kicked out and the information contained in the form gets lost, and it's not saved.
This are the specific parts of the index.php page:
<?php session_start(); ?>
<!DOCTYPE html>
[...]
<?php
if(isset($_POST['loguearse'])) {
$_SESSION['user']=strip_tags($_POST['user']);
$_SESSION['pass']=strip_tags($_POST['pass']);
if($_SESSION['user'] == 'myuser' && $_SESSION['pass'] == 'mypass') {
if (isset($_SESSION['user'])) {
session_start();
setcookie ("usuario",$_POST['user'], time()+24*60*60);
setcookie ("clave",$_POST['pass'], time()+24*60*60);
}
[HERE IT GOES THE CONTENT THAT WORKS OK IF I STRIP THE LOGIN CONTROL]
}
} else {
setcookie("usuario","");
setcookie("clave","");
echo '
<form method="post">
<div class="form-group">
<input type="text" class="form-control" name="user" id="user" placeholder="Usuario">
</div>
<div class="form-group">
<input type="password" class="form-control" name="pass" id="pass" placeholder="clave">
</div>
</div>
<div class="modal-footer">
<input type="submit" name="loguearse" class="btn btn-primary">
</div>
</div>
</form>
';
echo 'No puedes entrar sin poner la clave correcta!';
}
?>
My question is: How do I keep that user logged in and with an active session for 24 hours?
Your testing order is the problem here. You are originally testing for the POST variable, not the SESSION variable. Try this:
Test for logout to see if the user tried to logout. If so, delete the session.
Test for the session variables to indicate they're already logged in.
IF 1 and 2 are false, test for login. If so, initialize session.
It's the way you construct your if-conditions. Every time the user doesn't submit a post form you overwrite the cookie. The condition isset($_SESSION['user']) has to be on the highest level (at first) and then the post form check.
Also you run twice session_start(), one time is enough.
I use this for this exact thing and just include this in the header of any page.
<?php
#session_start();
// DB DEFINITIONS
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/db.php');
$db = db_connect();
if(isset($_GET['logout'])){
session_unset();
session_destroy();
if (isset($_COOKIE['cookuhash']) && isset($_COOKIE['cookfhash'])){
setcookie("cookuhash", "", time()-2592000,"/");
setcookie("cookfhash", "", time()-2592000,"/");
$uhash=$db->real_escape_string($_COOKIE['cookuhash']);
$fhash=$db->real_escape_string($_COOKIE['cookfhash']);
$db->query("DELETE FROM tblsessions WHERE USER_HASH='$uhash' AND FORM_TOKEN='$fhash'");
}
header("Location: /index.php");
exit();
}
if(!isset($_SESSION['loggedIn'])){
$_SESSION['loggedIn']=false;
$_SESSION['username'] = 'Anonymous';
$_SESSION['userid'] = 0;
$_SESSION['userlevel'] = 0;
$_SESSION['formToken'] = sha1(microtime());
}
if (!$_SESSION['loggedIn'] && isset($_COOKIE['cookuhash']) && isset($_COOKIE['cookfhash'])){
$uhash=$db->real_escape_string($_COOKIE['cookuhash']);
$fhash=$db->real_escape_string($_COOKIE['cookfhash']);
$result = $db->prepare("SELECT u.id,uname, lvl, user_lvl_expires FROM tblusers u LEFT JOIN tblsessions s ON s.USER_ID=u.ID WHERE USER_HASH='$uhash' AND FORM_TOKEN='$fhash'");
$result->execute();
$result->bind_result($id,$uname,$ads,$lvl,$expires);
$result->store_result();
if($result->num_rows > 0){
while ($result->fetch()) {
$_SESSION['loggedIn']=true;
$_SESSION['username'] = $uname;
$_SESSION['userid'] = $id;
$_SESSION['userlevel'] = $lvl;
$_SESSION['expires'] = $expires;
$_SESSION['formToken'] = sha1(microtime());
}
}
}
?>
Then in any page, just check:
#session_start();
if((!isset($_SESSION['loggedIn']) || $_SESSION['loggedIn']==0) && !isset($_COOKIE['cookuhash'])){
header("Location: /login.php");
exit();
}

Redirect loop issue in PHP website

I have been working on CS50's problem set 7, in which we have to make a financial website using MVC. I completed the website and it is working absolutely fine on my local machine.
But when I upload the files to hosting (free) service's server and try to access it I get a Redirect Loop error. Here is the link to it: http://ghazilajpal.byethost6.com/finance/public/
Here is code of login.php:
<?php
// configuration
require("../includes/config.php");
// if user reached page via GET (as by clicking a link or via redirect)
if ($_SERVER["REQUEST_METHOD"] == "GET")
{
// render form
render("login_form.php", ["title" => "Log In"]);
}
// else if user reached page via POST (as by submitting a form via POST)
else if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// validate submission
if (empty($_POST["username"]))
{
apologize("You must provide your username.");
}
else if (empty($_POST["password"]))
{
apologize("You must provide your password.");
}
// query database for user
$rows = query("SELECT * FROM users WHERE username = ?", $_POST["username"]);
// if we found user, check password
if (count($rows) == 1)
{
// first (and only) row
$row = $rows[0];
// compare hash of user's input against hash that's in database
if (crypt($_POST["password"], $row["hash"]) == $row["hash"])
{
// remember that user's now logged in by storing user's ID in session
$_SESSION["id"] = $row["id"];
$_SESSION["cash"] = $row["cash"];
// redirect to index.php (portfolio)
redirect("/");
}
}
// else apologize
apologize("Invalid username and/or password.");
}
?>
Update
Here is login_form.php:
<form action="login.php" method="post">
<fieldset>
<div class="form-group">
<input autofocus class="form-control" name="username" placeholder="Username" type="text"/>
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Log In</button>
</div>
</fieldset>
</form>
<div>
or register for an account
</div>
And this is config.php. This also has a redirect:
<?php
/**
* config.php
*
* Computer Science 50
* Problem Set 7
*
* Configures pages.
*/
// display errors, warnings, and notices
ini_set("display_errors", true);
error_reporting(E_ALL);
// requirements
require("constants.php");
require("functions.php");
// enable sessions
session_start();
// require authentication for all pages except /login.php, /logout.php, and /register.php
if (!in_array($_SERVER["PHP_SELF"], ["/login.php", "/logout.php", "/register.php"]))
{
if (empty($_SESSION["id"]))
{
redirect("login.php");
}
}
?>
I hope its easy to understand. I don't know where the problem lies and how to fix it.
I could have asked it on cs50.stackexchange.com but a similar question is already there with no answer.
Is it coming in this code block always?
if (crypt($_POST["password"], $row["hash"]) == $row["hash"])
{
// remember that user's now logged in by storing user's ID in session
$_SESSION["id"] = $row["id"];
$_SESSION["cash"] = $row["cash"];
// redirect to index.php (portfolio)
redirect("/");
}
if yes then here have a probelm.
change redirect with die(); to verify.
And Please provide some more inputs from you to clarify more.
I did some debugging using bhushanRJ's advice of using die (). And found out that the issue is with URLs. So using /finance/public/login.php instead of just login.php (same for other array items) solved the issue.
However CSS and JS files weren't loading. Similarly, fixing their URLs in templates fixed the issue.
When I got a loop it was because I hadn't started the session by putting "session_start()"

Redirect page when user is verified

i have this code to verify if users have Administrator account to backoffice of my website, but if user don't have it don't redirect user to ..index.php. He stay in this page but no content is shown.
Code of verification
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
}
else
{
echo "<script>alert(\"Area Restrita\");</scrpit>";
header("Location: ../index.php");
}
?>
In this page, (header) i call this file to verify session.
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
header("Location: ../index.php"); is not going to stop the rest of the code from running - if you just want to redirect him you should die(); or exit; right after you send the Location header
The alert part before the Location header is also unnecessary because the browser will redirect the user before he'll be able to see the alert. and also it is forbidden to call header function after you sent something to the output (for example, like you did with echo)
Another thing that you should consider - is the security issues that raised from validating user solely by looking at values in the $_SESSION - this means - that if someone is logged - you are not able to log him out until the session expires
The better way is to keep some token in the $_SESSION and save the status of the user in the database - that way, you can change his status directly from the DB without relying on the session/changing code
Your index file:
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
Your verification file:
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
// do some action for administrator
}
else
{
header("Location: ../index.php");
exit();
//echo "<script>alert(\"Area Restrita\");</scrpit>"; <-- you don't need this here
}
?>
Note, that I commented echo. You mustn't output anything before header. If you will output something (and you do in your example) you will get headers already sent error.
Your main mistake is you output something first and after that tried to redirect.
Anyway, I think better to use a bit another approach.
Form and form handler:
<?
$username = $_POST['username'];
$password = $_POST['password'];
// here is some query which will check if this user with this password exists and get the role of the user
// if exists $userExists = true; else $userExists = false;
if($userExists) {
$_SESSION['userLoggedIn'] = true;
if($role == 'administrator') {
$_SESSION['isAdministrator'] = true;
}
else
{
$_SESSION['isAdministrator'] = false;
}
header('Location: index.php');
exit(); // <-- don't forget this
}
else
{
// handler for bad user/password
}
?>
<form action='' method='post'>
<input type='text' name='username' />
<input type='password' name='password' />
</form>
Now, pages which are restricted will start from this code:
<?
$isAdministrator = $_SESSION['isAdministrator'];
if(!$isAdministrator) {
ban_ban_ban();
die('bye bye');
}
// content for administrator
?>
NOTE: This is just example, don't forget to add some check everywhere!!!!!11
But, as you wish :) Hope, this will help you.

AngularJS ngRoute and PHP $_SESSION variables

I have 3 pages:
index.php
login.php
display.php
index.php
Sets up AngularJS using the ngRoute module to navigate my pages.
login.php
Loaded by default and sets PHP $_SESSION variables.
display.php
Echos the contents of $_SESSION.
I navigate to display.php from login.php using a link setup with ngRoute.
Problem
display.php does not show $_SESSION variables no matter how many times I navigate to and from it. It will only display them if I manually navigate to the page such as refreshing the page or entering the address in the browser.
I know the php code is executed because I can echo other things to the screen it just doesn't access the $_SESSION variables.
Why is this?
I think i might see where your problem is. You try to access php session in your single page angularJS HTML templates am i right? like:
<div ng-repeat="n in <?php $_SESSION['someSessionArray'] ?>">
That is not how it works. Your $_SESSION will never be available in your templates.
What you can do, is use an ajax request for your login authentication and have that request give you a session id.
Then use that session id when starting your session in further ajax requests (as already mentioned).
Then, when you want to store something to the php session, access the data via ajax request and php service.
a VERY, VERY, VERY, simple Example:
inside getFromSession.php
session_start($_GET['session_id']);
$key = $_GET['key']
echo json_encode($_SESSION[$key]);
inside storeToSession.php
session_start($_GET['session_id']);
$key = $_GET['key'];
$value = $_GET['value'];
$_SESSION[$key] = $value;
inside your login.php
$user = yourAuthMechanism($_GET['username'],$_GET['password']);
if($user) {
session_start();
echo json_decode(array('status' => 'success','sid' => session_id()));
}
else { ... error handling
inside anywhere in your angular where you need to access session data:
$promise = $http.get('pathtoyourphp/getFromSession.php?key=foo');
$http.set('pathtoyourphp/getFromSession.php?key=bar&value=4');
// now use promise to acces the data you got from your service
In general, no reason exists, why AngularJS apps, which request
PHP-based server-side stuff, won't be able to read $_SESSION.
That said, please provide at least the core concepts of of your AngularJS code, so we can provide further details.
Additionally, put just this in display.php:
<?
echo __FILE__
. '<br />' . date( DATE_RFC822 )
. '<br />' . var_dump( $_SESSION )
;
// intentionally skipped dangerous closing PHP-tag
Now run your AngularJS app and tell what comes out.
Make sure you start the session before reading the SESSION variables.
<?php
session_start();
echo $_SESSION["user9"];
?>
I don't think you're looking for angularJS.
I think you're looking for something more like this.
index.php:
<html>
<header>
<title>Login</title>
</header>
<body>
<form method="POST" action="login.php">
<input type="username" name="username" placeholder="username" />
<input type="password" name="password" placeholder="password" />
<input type="submit" value="Login" />
</form>
</body>
</html>
login.php
<?php
session_start();
if(empty($_POST)) {
die("You don't have permission to be here.");
} elseif(empty($_POST['username']) or empty($_POST['password'])) {
die("All fields are required.");
}
$username = "admin";
$password = "password";
if($_POST['password'] == $password && $_POST['username'] == $username) {
$_SESSION['loggedIn'] == "true";
header("Location: show.php");
} else {
die("Invalid login");
}
?>
show.php
<?php
if($_SESSION['loggedIn'] == "true") {
echo "You are logged in";
} else {
die("You don't have permission to be here.");
}
?>

Categories