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.
Related
My logout.php file is like this. Is there any mistake in my code
logout.php
<?php
session_start();
session_destroy();
header('Location:index.php');
exit;
?>
Here is my index.php file. If I am set $_SESSION['s_activId'] then it is working properly but when I am trying to put condition if $_SESSION['s_activId'] is not set at that time I want to pass header on index page sometimes it works sometimes it does not work.
<?php
include('include/config.inc.php');
if(!isset($_SESSION['s_activId']))
{
$_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
header("Location:index.php");
}
else
{
$wrong = '';
if(isset($_POST['submit']))
{
$checkLogin = "SELECT userName,password,userType
FROM user
WHERE BINARY userName = '".$_POST['userName']."'
AND BINARY password = '".$_REQUEST['password']."'";
$checkLoginresult = mysql_query($checkLogin);
if($userLoginRow = mysql_fetch_array($checkLoginresult))
{
$_SESSION['s_activId'] = $userLoginRow['userName'];
$_SESSION['s_password'] = $userLoginRow['password'];
$_SESSION['hg_userType'] = $userLoginRow['userType'];
if(!$_SESSION['s_urlRedirectDir'])
{
header("Location:index.php");
}
else
{
header("Location:reminder.php");
}
}
else
{
$wrong = "UserId And Password Is Not Valid";
}
}
}
include("bottom.php");
$smarty->assign('wrong',$wrong);
$smarty->display("index.tpl");
?>
The problem arise in the condition below in index.php:
if(!isset($_SESSION['s_activId']))
{
$_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
header("Location:index.php");
}
When you logout, you are calling session_destroy() on logout.php and redirecting on index.php and the condition above gets true as s_activId is not set in session and again you are redirecting on index.php (without setting s_activId in session). The above condition will be true until the variable s_activId set in session and because of this you are getting ERR_TOO_MANY_REDIRECTS error.
The solution is, on index.php set the variable s_activId in session before calling the header method. Refer the code below:
if(!isset($_SESSION['s_activId']))
{
$_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
$_SESSION['s_activId'] = true;
header("Location:index.php");
}
Dont redirect index.php to index.php. you having redirects loop. Also
if you have code below that also can fire add die in if because after
redirect code below still executes. I didnt read your code, maybe
there isnt problems with this but after
header("Location: lalala"); always add die(); or exit();
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.
i have a multi step form and want to condition users on specific sites on my web .
This mean i want that only after submitting my form a client in my case can see the redirected page ,
And that with a kinda tim-out for that page to . this redirected page need to show only to those people who fill the form first even when users copy the link and give that link to somebody else the link should not work or should direction in a error. i have archived the last part partly
Here is all my code :
On the form.php i have this :
<?php
session_start(); $_SESSION['form_finished'] = true;
?>
On the proces.php i have this :
$emotion = $_POST['emotion'];
if($emotion == 'Basic Pack') {
session_start();
$_SESSION['form_finished'] = true;
header('Location: /new/basicc.php');
} elseif($emotion == 'Deluxe Pack') {
header('Location: html6.php');
} elseif($emotion == 'Premium Pack') {
header('Location: html7.php');
}
and destination site in this case basicc.php' this :
<?php
session_start();
if(!$_SESSION['form_finished']) {
header("HTTP/1.0 404 Not Found");
exit;
}
?>
This code is working partly because if the user on the form.php site if he just copy the basicc.php link on the address bar he can see the basic.php site imadtitly without having to fill the form , and i want that to condition him to do that and than the page to show up .
I hope i was clear thanks in advance
If proces.php is where submitting the form redirects then remove $_SESSION['form_finished'] = true; from form.php and keep it in proces.php only.
ETA: For the timer:
<script>
var remainingSeconds = 600; // how many second before redirect
function counter() {
if (remainingSeconds == 0) { clearInterval(countdownTimer); window.open('form.php', '_SELF'); // return to form page
} else { remainingSeconds--; }
}
var countdownTimer = setInterval('counter()', 1000); // 1000 is the interval for counting down, in this case 1 second
</script>
In this case, you will have to add back the statement in form.php but set it to false $_SESSION['form_finished'] = false;
ETA2: Forgot to mention that you should also add $_SESSION['form_finished'] = false; in basicc.php.
Yes you could just use a simple session for this case. Example:
If in your form action, if the form processing is in process.php. You could initialize there the session.
session_start();
$emotion = $_POST['emotion'];
$_SESSION['form_finished'] = true; // set session
// then your other process etc. etc.
if($emotion == 'Basic Pack') {
header('Location: /new/basicc.php');
} elseif($emotion == 'Deluxe Pack') {
header('Location: html6.php');
} elseif($emotion == 'Premium Pack') {
header('Location: html7.php');
}
And then on the destination files: /new/basicc.php and others, check that session existence:
/new/basicc.php and others:
if(isset($_SESSION['form_finished'])) { // so after redirection check this
//
// hello, i came from process.php
unset($_SESSION['form_finished']); // and then UNSET it! this is important
} else {
echo 'not allowed'; // if this is not set, the page is directly accessed, not allowed
exit;
}
I think the best solution is that you should only use one page, no need for sessions ;)
Try to have a particular variable set to false, send your form to the server using a POST method <form method=post> and on your server, change this variable to true and render the same page again.
In the example below, I'm checking if the user has entered his name in the form. ;)
<!-- In form.php -->
<?php
$formSubmitted = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST["name"])) {
//Do what you need to do with form data, for example:
$name = filter_var($_POST["name"],FILTER_SANITIZE_STRING);
//Maybe do some checks on the data (or add to database) and when successful:
if($name != '')
{
$formSubmitted = true; // Set variable to true
}
}
?>
<?php if($formSubmitted): ?>
Hello <?php echo $name; ?>! <!-- Show all other HTML things you want to show -->
<p> This is a message only for people who submitted the form! </p>
<?php else: ?>
<form action='form.php' method='POST'>
<input name='name' type='text'>
</form>
<?php endif; ?>
I hope it'll be useful and hopefully a different way to look at the problem. For multi-step, this could easily accommodate more variables to see which step the user is on ;)
Good luck :)
Here is my login form. aka index.php
<form class="form-3" action="login.php?log=ok" method="post" >
<input type="text" name="username" id="login" placeholder="Username">
<input type="password" name="password" id="password" placeholder="Password">
<input type="submit" name="submit" value="Submit">
</form>
And here is my login checker. aka login.php
<?php
require_once 'classes/Personel.php';
$personel = new Personel();
$personel->setUsername($_POST['username']);
$personel->setPassword($_POST['password']);
$personel->login();
header("Location: index.php");
// REDIRECT
session_start();
if (strcasecmp($personel->getRole(), "LTO") == 0 ) {
$_SESSION['role'] = "LTO";
$_SESSION['personel'] = $personel;
header("Location: LTO");
}else if(strcasecmp($personel->getRole(), "LTFRB") == 0){
$_SESSION['role'] = "LTFRB";
$_SESSION['personel'] = $personel;
header("Location: LTFRB");
}else if(strcasecmp($personel->getRole(), "LGU") == 0){
$_SESSION['role'] = "LGU";
$_SESSION['personel'] = $personel;
header("Location: LGU");
}else if(strcasecmp($personel->getRole(), "ADMIN") == 0){
$_SESSION['role'] = "ADMIN";
$_SESSION['personel'] = $personel;
header("Location: admin");
}
?>
now when i try to access any accounts from them i can easily open its index page and other pages even i'am not login. How can i prohibit that? and how can i avoid the url rewriting?
eg. the index page of admin
try to open my link the correct account is admin-admin also try a wrong one..
Big Thanks in advance.
First thing, you need to set the redirect to index.php in proper place, with some condition.
I get your problem, but are you checking the session on each and everypage?
You need to implement a check at the beginning of each page that whether the session is properly set or not. Else redirect back to index.php.
You need to implement this code before each of your pages:
session_start();
if(isset($_SESSION['role'])){
if($_SESSION['role'] != "ADMIN") { //change the "ADMIN" to your unique role per page
echo "Access denied";
exit();
}
else {
header("Location: index.php");
}
You are calling header("Location: index.php") without any condition.
That means that you are always redirecting to index.php.
Any call to login.php will result in automatic redirect to index.php.
I don't know what $personel->login() exactly does but your code should look something like:
$authorized = $personel->login();
if (!$authorized) {
header("Location: index.php");
exit();
}
Also - session_start() should be at the top of the code.
Hope this helps!
You can place a check at the top of every page, and if user not logged in redirect them to an appropriate page, for example a login page.
Here's one approach to doing this.
When you login, set a $_SESSION variable (something like user_id), like this:
//If successful login:
$_SESSION['user_id'] = $userid_from_the_db;
Note that when using sessions, you must place session_start(); at the very TOP of each page.
Then, you can check if the user is logged in before displaying any page data.
Something like:
<?php
protect_page();
Where protect page can look like this:
if (isset($_SESSION['user_id'])===false) {
echo '<p>Please log in first</p>';
echo '<meta HTTP-EQUIV="REFRESH" content="5; url=login.php">';
}
Consider viewing this (free) tutorial from phpAcademy:
Registration and Login - Procedural version
Registration and Login - OOP version
Notes:
You can use either of these methods to redirect the page:
header("Location: pagename.php");
This is the preferred way, however you cannot output any other headers before using this command or it will fail.
<meta HTTP-EQUIV="REFRESH" content="5; url=pagename.php">
As a work-around, you can use this method to redirect the page, and the bonus is that it will wait the specified number of seconds before doing so (5 in this case, or zero if you choose).
I'm trying to get a login on a website where it connects to the database, checks against it, but the redirect isn't working (login.php to loggedin.php). I am appalling at proof reading my own code and have been going round in circles for a while. If someone could assist I would be very grateful! Thank you in advance.
Login_page.inc.php
<?php # Script 11.1 - login_page.inc.php
// this page prints any errors associated with logging in
//and creates te entire login page, including the fom
//include the header:
$page_title = 'Login';
include ('includes/header.html');
//print any error messages if they exist:
if (!empty($errors))
{
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:</br>';
foreach ($errors as $msg)
{
echo "- $msg</br>\n";
}
echo '</p><p>Please try again.</p>';
}
//display form
?>
<h1>Login</h1>
<form action=login.php" method="post">
<p>Email Address: <input type="text" name="email" size="20" maxlength="80"/></p>
<p>Password: <input type="password" name="pass" size="20" maxlength="20"/></p>
<p><input type="submit" name="submit" value="Login"/></p>
<input type="hidden" name="submitted" value="TRUE"/>
</form>
<?php //include the footer:
include ('includes/footer.html');
?>
Loggedin.php
<?php # loggedin.php
//this is where the user is directed from login.php
session_start();
//if no cookie is present redirect the user:
//if (!isset($_COOKIE['user_id']))
if (!isset($_SESSION['user_id']))
{
//the functions need to create an absolute url
require_once ('includes/login_functions.inc.php');
$url = absolute_url();
header("Location: $url");
exit(); //exit script
}
//set the page title and include the header
$page_title = 'Logged in.';
include ('includes/header.html');
//welcome message
echo "<h1>Logged in!</h1>
<p>You have successfully logged in, {$_SESSION['first_name']}!</p>
<p>Logout</p>";
include ('includes/footer.html');
?>
Login.php
<?php # login.php
//this page processes the login form submission
//upon successful login the user's redirected
//two include files are needed for this
//send nothing to the web browser prior to the setcookie() lines
//check if the form has been submitted:
if (isset($_POST['submitted']))
{
//for processing the login:
require_once ('includes/login_functions.inc.php');
//need the database connection:
require_once ('includes/mysqli_connect.php');
//check the login
list ($check, $data) = check_login($dbc, $_POST['email'], $_POST['pass']);
if($check)
{
/*ok, set cookies to last one hour after it is set
setcookie ('user_id', $data ['user_id'], time()+3600, '/', '', 0, 0);
setcookie ('first_name', $data ['first_name'], time()+3600, '/', '', 0, 0);*/
session_start();
$_SESSION['user_id'] = $data['user_id'];
$_SESSION['first_name'] = $data['first_name'];
//redirect
$url = absolute_url ('loggedin.php');
header("Location: $url");
exit(); //quit the script
}
else
{
//assign errors to $data for error reporting in the login_page.inc.php
$errors = $data;
}
mysqli_close($dbc); //close the database connection
} //end of main submit condition
include ('includes/login_page.inc.php');
?>
Login_functions.php
<?php #- login_functions.inc.php
//this page defines two functions used by the login/logout process.
/*this function determines and returns an absolte URL
*takes one argument: the page that concludes the URL
*the arguement defaults to index.php
*/
function absolute_url ($page = 'index.php')
{
//start defining the URL. . .
//URL is http:// plus the host name plus current directory:
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
//remove any trailing slashes:
$url = rtrim($url, '/\\');
//adding the page. . .
$url.= '/' . $page;
//return to the url
return $url;
} //end of the absolute_url function
/* this function validates the form data (the email address and password)
*if both are present the database is queried
*this function requires a database connection
* the function returns an array of information. including:
* - a TRUE or FALSE variable indicating a success or failure
* - an array of either errors or the database return result
*/
function check_login($dbc, $email = '', $pass = '')
{
$errors = array(); //starting error array
//validate email address
if (empty($email))
{
$errors[] = 'You forgot to enter your email address.';
}
else
{
$e = mysqli_real_escape_string($dbc, trim($email));
}
//validate the password
if (empty($pass))
{
$errors[] = 'You forgot to enter your password.';
}
else
{
$p = mysqli_real_escape_string($dbc, trim($pass));
}
if (empty($errors))
{
/*if everything's okay
*retrieve the user_id and the first_name for that
*email+password combination:
*/
$q = "SELECT user_id, first_name FROM site_users WHERE email='$e' AND pass=SHA1('$p')";
$r = #mysqli_query ($dbc, $q); //run the query
//check the result and making sure that both fields are in the same row
if(mysqli_num_rows($r) ==1)
{
//fetch the record
$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
//return true and the record:
return array(true, $row);
}
else
{
//not a match
$errors[] = 'The email address and password entered do not match those on file.';
}
}//end of empty($errors) IF.
//return false and the errors:
return array(false, $errors);
} //end of check_login() function
?>
If any of the files contains any code that gets sent to the browser, PHP sends all the headers automatically. After the headers have been sent, you can no longer send new headers, and it drops your Location: header. PHP should be throwing a notice, look for it in your logs and/or set the correct error_reporting flags.
This includes newlines or spaces or whatever that is after an ?> tag block.
There is nothing wrong with your script from what i can see ... here but am not sure of the content of
includes/header.html
index.php
You need to also replace
<form action=login.php" method="post">
with
<form action="login.php" method="post">
If you can paste the error you are seeing .. maybe i can help you better
Thanks
:)
Don't include any blank line before your header('Location: $url'). Because this prevents sending header and you are not able to get redirect to place where you want to be.
The issue was within the SHA1 talking to the database, where by SHA1 is a (40) strong and the database was set to (20). An annoying issue but it has not been resolved. Var_dump was used to talk to the database to prove that the information being entered was correct, it did however show that the password held in the database was (20) and the password entered for login was (40).