Can you please let me know why my session setting is not working correctly? I have a simple Form in index.php file as:
<?php
session_start();
$_SESSION['uid'] = 'test';
?>
<!DOCTYPE HTML>
<html>
<body>
<form method="POST" action="validate.php">
Password: <input type="text" name="name" value="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
I also have a validate.php file which is like this:
<?php
session_start();
$err="You Have to Insert The Password to Get into Page";
if(($_POST['name']) == $_SESSION['uid']){
header ("Location: target.php");}
else{ echo $err; }
?>
and finally the target.php page is like this
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<body>
<img src="session.jpg">
</body>
</html>
Now my problem is when ever I run the validate.php or target.php URLs directly from the browser address bar like (..localhost/PHP/Session_3/validate.php) I still get access to the target page!
Can you please let me know why this is happening? and how I can set a better isset() function to prevent this?
Thanks for you time and comments
You have to check for session on every page you load,
Adding
if(!isset($_SESSION['uid'])){
header ("Location: index.php");
}
may help on each page. And dont forget to delete the session on every logout.
//Four Steps to close a session
//i.e. logging out
//1. Find the Session
session_start();
//2. Unset all the session variables
$_SESSION=array();
//3. Destroy the session cookie
if(isset($_COOKIE[session_name()])){
setcookie(session_name(),'',time()-42000,'/');
}
//4. Destroy the session
session_destroy();
//redirect_to("index.php?logout=1");
You have code to validate a password but that's all you've written so far. You are neither storing the result of the validation, nor preventing access to protected pages.
To store validation result:
if ($_POST['name']==$_SESSION['uid']) {
$_SESSION['validated'] = true;
}
To protect a page:
if (!isset($_SESSION['validated'])) {
header('Location: http://example.com/');
exit;
}
($_POST['name']) will return a Boolean value, its an if statement on his self ( because of the ( and ) you put around it. It will give you a true value when the $_POST is available.
So what you get is if ((True) == $_SESSION['uid']). Because the code sees the True value it will not run the code after it, its allready true in it.
Thats why it always comes the the header line
So this should do the trick in your case ( there are better ways to do it btw )
if($_POST['name'] == $_SESSION['uid']){
header ("Location: target.php");
}
else
{
echo $err;
}
You have almost done it. There is no need of validate.php. just copy below code in index.php,
<?php
session_start();
if(!empty($_POST['name']) and ($_POST['name']=='test') ){
$_SESSION['uid']='test';
header ("Location: target.php");
}
?>
and update form action to
<form method="POST" action="**index.php**">
and in index.php form, use below code.
<?php
session_start();
if(empty($_SESSION['uid'])){
header ("Location: index.php");
}
?>
You can access target.php if you close and reopen browser. Because at the start there is no value in session and post
So this line,
if(($_POST['name']) == $_SESSION['uid'])
equals
if ( "" == "" ) //true
You should use isset(),
validate.php
<?php
session_start();
$err="You Have to Insert The Password to Get into Page";
if (isset($_POST['name']) && isset($_SESSION['uid'])) {
if ($_POST['name'] == $_SESSION['uid']) {
$_SESSION["logged"] = "logged";
header ("Location: target.php");
} else {
echo $err;
}
} else {
header ("Location: index.php");
}
?>
And If you want to make target.php inaccessible directly if not logged, That would be like this,
target.php
<?php
session_start();
if (!isset($_SESSION["logged"])) {
//No access directly if not logged
header ("Location: index.php");
}
?>
<!DOCTYPE HTML>
<html>
<body>
<img src="session.jpg">
</body>
</html>
Related
login.php
<?php
ob_start();
session_start();
include '../config.php';
if( (isset($_SESSION['can-id']) )) {
header('location: ../home/profile.php');
}
if(isset($_POST['can-login']))
{
$email=$_POST['email'];
$password=$_POST['password'];
$sql="SELECT * FROM `user_credentials` WHERE `email`=:email AND `password`=:password";
$pdoResult=$conn->prepare($sql);
$pdoExec=$pdoResult->execute(array(":email"=>$email,":password"=>$password));
$pdoResult->setFetchMode(PDO::FETCH_ASSOC);
$count=0;
$uid='';
while ($r=$pdoResult->fetch()) {
# code...
$count+=1;
$uid=$r['email'];
}
if ($count==1) {
# code...
$_SESSION['can-id']=$uid;
header('location: ../home/profile.php');
}
else
{
$_SESSION['error']="login failed";
}
}
?>
<html>
....
</html>
profile.php
<?php
ob_start();
session_start();
if (!(isset($_SESSION['can-id']))) {
# code...
header('location: ../login/');
}
else
{
$cid=$_SESSION['can-id'];
}
?>
<h1 ><?php echo $cid;?></h1>
This is my code after log in the page was redirected to profile.php page but in profile page session variable doesn't printed I don't know why but this problem was not occuring every time I log in It occurs sometimes so I can't find what is the problem. Anyone knows please help me to solve the problem.
Remove ob_start() from your login.php
Don't put session_start() in all of your file
e.g login.php, profile.php, etc
but instead, add this to your config.php for example:
<?php
session_start();
//.. config variables here
Then, include config.php also in your profile.php.
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.
i am submitting a form and then using header redirect to take the user to a new page. how can i add a session to my header redirect to say once user has been redirected echo out a div within a session saying something like form submitted?
heres what i have tried to do but can not get it to work, can someone please point me in the right direction, thanks.
submit_form.php:
header("Location: ../index.php?success=$success");
index.php:
<?php echo $_SESSION['success']; ?>
<?php $success= "<div> CONGRATULATIONS!!!!!</DIV>"; ?>
A session value is something stored in a session started with session_start().
What you have is a URL query parameter, which you can access with $_GET['success'].
submit_form.php:
session_start();
$_SESSION['success'] = true;
header("Location: ../index.php?success=$success");
index.php:
session_start();
if (isset($_SESSION['success']) && $_SESSION['success']) {
//Echo your div
}
You appear to be mixing up $_SESSION and $_GET
Try below code:
On submit_form.php page:
$_SESSION['success'] = "YOUR SUCCESS MESSAGE";
header("Location: ../index.php");
On index.php page:
if(isset($_SESSION['success']) && $_SESSION['success']!=""){
echo $_SESSION['success'];
unset($_SESSION['success']);
}
On both page, on top, put below code:
session_start();
I have a simple authentication: you login in the login.php page and you are redirected to the home.php page.
This is the code of login.php:
if(pg_num_rows($rs) == 0){ //I search in db for a row with username and password
$errMess = "error";
pg_close($conn);
}else{
$row = pg_fetch_row($rs);
session_start();
$_SESSION['username']=$_POST["nick"];
$_SESSION['admin'] = $row[0];
pg_close($conn);
header("Location: /home.php");
}
now in the home I have the header done in this way:
<?php require_once("scripts/functions.php");
require_once("scripts/config.php");
session_start();
?>
<div id="siteHeader" class="headersLeft"><?php echo WELCOME;?></div>
<div id="userContainer" class="headersRight">
Logged as: <?php echo getDisplayName(); ?>
<?php if(isset($_SESSION['username'])) {?>
<button class="button" onclick="location.href='/logout.php';">logout</button>
<?php }else{ ?>
<button class="button" onclick="location.href='/login.php';">login</button>
<?php }
?>
</div>
it doesn't work: even if data is correct it still gives me "guest", the session variable is lost in the header passage..how come?
Solved: i was under windows and the default path to the temp folder, where php actually saves session files, was wrong: was "/tmp" and was not recognized.
I set it to "C:\php\tmp" and it worked: session file was not saved at all!
Write session_start(); on top of everything (right after
<?php
session_start();
require_once("scripts/functions.php");
require_once("scripts/config.php");
?>
or if still doesn't work then write your code like this:
<?php
ob_start();
session_start();
require_once("scripts/functions.php");
require_once("scripts/config.php");
?>
Also don't forget to put these two lines at the top of your login.php page.
Hope it helps :)
I'm guessing there's some more code after the if statement that continues to manipulate $_SESSION. That's where $_SESSION['username'] is assigned the 'guest' value.
Remember, header("Location: /home.php"); only sets a response header. It doesn't redirect immediately, stopping script execution.
Place a exit; command right after header() to prevent execution from reaching the rest of the code:
header("Location: /home.php");
exit;
this works for me:
session_save_path ( "" ) ;
session_start();
so I need to figure out how I can get my else statement to return to my previous function which is passprotect.html (the file I start on).
So I write in my password and click submit.
When I hit submit it checks with my PHP if the password is correct or not.
If the password is correct it writes "You did it!".
If it is wrong I want it to return back to the passprotect.html site with an error message saying, "Wrong password, try again!".
Here is my two codes:
<html>
<body>
<title>FriedBitz</title>
<form action="secret.php" method="post">
Password: <input type=password name=pass></input>
<input type=submit value=Enter>
</form>
</body>
</html>
and
<html>
<body>
HERE IS YOUR RESULT
<?php
if ( $_POST['pass'] === 'test')
{
echo "You did it!";
}
else
{
header('Location:www.example.com');
}
?>
</body>
</html>
So as the Marc B noted you can not use header that way.
From the php.net manual -> 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.
If you have no option to change layout's of your project files (removing outputs before headers are sent) i suggest you to use ajax for this kind of work.
Or you need to place clickable link for user on a page instead of header.
Example of working header with your code:
<?php
if ( $_POST['pass'] === 'test')
{
$output = 'You did it!';
}
else
{
header('Location:www.example.com');
exit;
} ?>
<html>
<body>
<?php echo $output; ?>
</body>
</html>