Session is not maintained - php

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();

Related

How to call a script every time a user logs in (or whenever a session is active)

I am trying run a script called random_post_generator.php which should execute every time a user is logged in.
I am using this approach as an alternative to cron.
Here is how my session is currently created:
<?php
ob_start();
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: index.php");
} else {
$username = $_SESSION["user_login"];
}
?>
But how do I say - "if session is active, then run this script"?
<?php
ob_start();
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: index.php");
} else {
$username = $_SESSION["user_login"];
include 'random_post_generator.php';
}
?>
or you can use require 'random_post_generator.php'
If I understood correctly, you are trying to find out how to include a script of php (that is located in an outside .php file) inside your current file while using your previous code that checks if a user is logged in:
<?php
$root_directory_path = $_SERVER['DOCUMENT_ROOT'];
ob_start();
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: index.php");
} else {
$username = $_SESSION["user_login"];
$pathName = $root_directory_path."myScript.php";//I am assuming here
//the script is located inside the root directory, and not in a sub
//directory
require($pathName);
}
?>
just remember that whatever php code is inside myScript.php has to have the <?php ?> tag surrounding it. Your code does not reuse the <?php ?> tag of the "calling" file.
Let me know if that worked for you

PHP Header redirect and echo out session on next page?

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();

Variable $_SESSION does not work PHP

I want to add a simple "login/logout" script to my web site but it does not work.
<?php if(isset($_POST["signin"])){
session_start();
$username=stripslashes($_POST["username"]);
$password=stripslashes($_POST["password"]);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$nom=checkUser($username, $password);
if(!$nom=="")
{
$_SESSION['name'] = $nom;
header("location:account.php");
}
else {
echo 'WRONG USERNAME OR PASSWORD';}
}?>
the script above is header.php which means it's included in every single page; now here is the page of "account.php"
<?php if(isset($_SESSION['name']))
{
include('header.php');
echo'
</article>
<article class="col1 pad_left1">
<p>Bienvenue '.$_SESSION['name'].'</p>
</article>
</header>
</div>';
include('footer.php');}
header("location:index.php");
?>
The problem is that i always get to the index.php even if i'm logged in as if this test if(isset($_session['name'])) is always false.
I guess you rather want to use if($nom!="") than if(!$nom==""). Additionally, you need to call session_start() before you can use $_SESSION (you're doing it the other way round at the moment).
you have to start session in every page at the top by
session_start();
probably you are missing this.
Try to add session_start(); before if(isset($_SESSION['name'])) and check if it's a blank lines in your files at the top and in the end.

Php login hide when logged in and hide logout when not logged in

I want a code to hide login button when logged in and display "welcome,username" and the logout button and when not logged in to display the login button...
http://needforgaming.x10.mx/testefinal/home.html This is my website you can see how it looks idk if it is where i put the code thaths wrong or the code
<?php
session_start();
if(isset($_SESSION['username'])){ ?>
<p>Ola; <u><?php echo $_SESSION['username']; ?></u>, </p>
<p>Logout</p>
<?php } else{ ?>
<p>Login</p>
<?php } ?>
There is another easy method. You can start session firstly. Then use this code:
<?php
if(!isset($_SESSION['user']))
{
echo '<li>Login</li>';
}
else
{
echo '<li>Logout</li>';
}
?>
actually this code is for using login/logout in . You can use it where ever you need. Just change the html tags. That's it
I think you are using plain html .. your page needs to be of php to run this code on a apache/IIS server, code is good enough to work.
You may want to check for emptiness. Change:
if(isset($_SESSION['username'])){ ?>
to
if(isset($_SESSION['username']) && !empty($_SESSION['username'])){ ?>
You've put PHP code to .html page. Either switch it to .php, or configure your server to evaluate .html as PHP too.
Take a look at Your first PHP-enabled page, it should provide sufficient details.
you should make all the block a php code:
<?php
session_start();
if(isset($_SESSION['username'])){
echo "<p>Ola; <u> $_SESSION['username']; </u>, </p>";
echo "<p>Logout</p>";
} else{
echo" <p>Login</p>";
}
?>

Having Issue with PHP Session

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>

Categories