session variables not working across different pages - php

Once i logged in i set a session variable inside body element(inside login.php) as below:
session_start();
$_SESSION['Username'] = $_POST["Username"];
if(isset($_SESSION['Username']))
$loginTrue = 1;
else
$loginTrue = 0;
and on top every page i have added this
<?php
session_start(); //this was added after seeing many suggestions in stack overflow that session_start() has to be called at the top on each page. Though i tot calling once was sufficient.
if(isset($_SESSION['Username']))
$loginTrue = 1;
else
$loginTrue = 0;
?>
Now whenever i redirect my page after login from login.php $_SESSION['Username'] gets unset, i dont know how. I redirect using a button click as in
onclick execute window.location = home.php

This is not comman
check your code with this code may be some error is on the page
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
?>
And check your php.ini setting for this.
And check your code with different browser.
And any blank output should be on your page before session start.

alright guys i solved it somehow. I dont know how i did but i did. Firstly i created 4 webpages, a small one just to check the if session variables are supported. Once i confirmed this then i did the below and my original webpage started working session start is very important at top of all pages. Also try session activity in different browsers. Also check by closing dreamweaver. Also make sure is used instead of transitional and stuff and also that session start comes before doctype html declaration

Related

Trying to redirect based on session variable existence but it's not working

I want to ensure that an HTML page only appears if the user has logged in. I'm trying to do it by setting a session variable from the login page then checking if that variable exists when the HTML page is loaded.
This is my code at the very top of the HTML page:-
<?php
session_start();
if (!isset($_SESSION['checks'])) {
header("location: http://localhost/project/fail.php");
}
?>
It doesn't redirect! Nothing happens at all except that the HTML page gets loaded.
Can anyone help please?
Thank you all for your helpful suggestions. The snippet I posted shows the very first lines: i.e. session_start(); is the very first line.
By moving the var check snippet from the session_start() segment and making a separate php check snippet immediately after the body tag, everything works as expected.
You can use header function : https://www.php.net/manual/en/function.header.php
Referring to it :
<?php
session_start();
if (!isset($_SESSION['checks'])) {
header("Location: http://localhost/project/fail.php");
}
?>
make sure that session_start() always come at the first line
if(!isset($_SESSION['checks'])){
header('location: fail.php');
}
I believe your problem is on the login page... Although, if I were to talk about this page, consider trying the following code instead of your snippet first. If it gives the desired outcome then you will know that the problem is with your header and not the session:
<?php
session_start();
if (!isset($_SESSION['checks'])) {
echo "not logged in";
}
?>
Do make sure you're referring to the correct session variable if this code doesn't work and feel free to share how you are starting this session on your login page.

Session not working for first time, from second time it works

I don't know what is the problem. When I do login for first time after deleting all history and cookies and cache, it doesn't set session to redirected page. But when I do login for second time, session is set to redirected page. Here id the code of First & second page.
First Page
<?php
session_start();
include('includes/connection.php');
$email=$_POST['email'];
$password=$_POST['password'];
$data=mysqli_query($GLOBALS["___mysqli_ston"], "select * from user_registration where email='$email' and password='$password' ");
$data1=mysqli_num_rows($data);
$val=mysqli_fetch_array($data);
if($data1>0)
{
$_SESSION['user_id']=$val['user_id'];
echo "<script>window.location.href='index.php'</script>";
}
else
{
echo "<script>window.location.href='login.php'</script>";
}
?>
Second Page
<?php
session_start();
$val=$_SESSION['user_id'];
echo $val;
?>
session_start(); should be at the very top of both scripts!
Session variables are saved on server and assigned a unique code that are passed to browser in cookies.
Because the cookies are set by the headers they need to be sent before anything else!
Even a whitespace at the top of your script may cause session cookie to be not properly set on browser side.
So always start the both scripts like this:
<?php
session_start();
// Rest of the code....
It looks like they are on top on your question but I think you edited question later to put there.
That's the only reason sessions are not working the first time and they are working on second time.
instead of the echo use
header("Location: index.php");
EDIT
alsosession_start should be declared at the top of the first page because you cant set a session that doesn't exist in the context if you were running it in a console environment you would receive the following error
"$_SESSION['user_id'] does not exist in the current context"
same happening here. is php 5.6 is super strange problem. on some pages work normaly and on one dont. First request is like dont get recognized.. :)
for example: set
#when page load set:
$_SESSION['a']=0;
#then with JS requests increase $_SESSION['a']+=1; and this start working on third request...

declaring session variables php

Is it not mandatory to use session_start() before using any session variables in PHP?
I tried the following piece of code without declaring session_start() at the beginning, it worked fine.
So, now I'm confused. Please help !!!!
Also, I did not use any $_POST or $_GET to pass $uname to home.php, but still how does it work? If we use include 'home.php' then does it treat login.php and home.php as same page?
// code login.php//
<?
require_once 'db_connect.php';
if (isset($_SESSION ['user_id']) && !empty($_SESSION ['user_id']))
{
$u_name = $_SESSION['user_name'];
include 'home.php';
}
else
{
//some stmt
}
?>
/*******home.php file ****/
<?php
require_once 'dbconnect.php';
$_SESSION['username'] = $u_name;
//echo $_SESSION['username'];
//blah blah
?>
You definitely need it, if session.autostart is not set in php.ini. But you would probably know that then.
Do you not call it in db_connect.php? Also, I'm pretty sure you wouldn't get any errors, the session would just be empty.
If you include a file via php, Session keeps active (as any others variables set too). If you would access this file as new request, you would need to set session_start().
This behaviour is because include and require act like moving the code of the included file into the current one, as you would have typed the code into one single file.
Plus: you don't need to require dbconnect.php twice.
edit: you asked about both files used as the same page - the page is the output given after the whole php code is done. The page itself doesn't care about how many files internally are used for generating it.
Use the session_start () is obligatory for every session in php. Being passed through a variable values ​​is not necessary to make POST or GET the same, since there is already the case the value increment. If not ouver value in the same session is null or blank, if you open the page in the same way the condition is wrong.
(!Isset($_SESSION ['user_id']) &&!​Is_Null($_SESSION['user_id']))
isset to check if empty this need! before, IF(!isset($_SESSION['user_id']) and in the second case would be to check if it is not null and void, for a session either exists or does not exist and if a value is set inesistente is null. So correct view is this: is_null($_SESSION ['user_id'])
Importantly, in the login page does not include but redirect to the page. in the case with a header.
Or could do everything in a single page, but it would not be legal to display on a page called login page. The default would be the index, ie if the login stay within a folder, you place it inside the index page and the address of the folder.
The reason for the session can still open is that sometimes the webserver does not realize that erased part of the code and loads of it from the system cache.

php sessions not being detected

I have a login page that I register two sessions username and password. then redirect to another page. Once at this page
$_SESSION['username'] = "";
$_SESSION['password'] = "";
after login check I have the next page check if the session is registered
session_start();
if(isset($_SESSION["username"]){
continue
}else go back to login page
Once I'm logged in I want to go to another page that depending on if the session variable is set I display something different on the page.
So on the galery page I do
at the very top of page I do
<?php
session_start();
?>
then further down where I want the button to be I do
<?php
if (isset($_SESSION['username'])){
show a new button
}
?>
I get the button to show but at the top of the page I have
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent
and it messes up how my page is displayed. Any ideas? I have the session_start(); at the very begging of page I don't know why this is happening. Any ideas?
You'll get that error if anything outputs to the browser before you call session_start(). For example, you can't do:
<?php
echo "Test";
session_start();
You also can't do:
<?php session_start();
(note the space before the <?php)
Make sure nothing - no HTML, no blank lines, no spaces - is written out prior to your session_start() calls and you'll be fine.
You need to ensure there's nothing (whitespace, UTF-8 BOM) before your <?php. This also applies to any files you include before the session_start() call.
Is the gallery page being included in another file?
<?php
// lots of php code
include('/path/to/gallery.php');
?>
If anything is being sent to the browser before the session_start(); it will create this error.
Session is a header, headers can't be sent after any output (even a single space). You got 2 options, place session_start() before ANY output or you could also use output buffering, this allows you to send headers after output.
Place this at the top of your script
ob_start();
And this at the end
echo ob_get_clean();

PHP Session Variables - disappear and reappear

I have a template file that contains all my header, footer and common information. It includes the appropriate content for the current page (two-step view pattern).
I am trying to set up a login system using PHP Session variables. I can set the variable and sometimes they work but sometimes they disappear. Clicking on links will sometimes make them come back.
My site
Login with
username: test
password: test
There are var_dumps of session_id and $_SESSION at the top.
Click on Home. If the session variables disappear click on home (might take as many as 10 times) to see the session information come back. Click on the other navigation and sometimes the session info sticks around and sometimes it doesn't.
Here is the session code at the top of my template file.
<?php
session_start();
require './classes/DBInterface.php';
$db = new DBInterface();
if($_REQUEST['submit'] == 'Login') {
$username=$_POST['username'];
$password=$_POST['password'];
echo '-- login -- '.$username;
$rs = $db->verify($username,$password,"admin",0);
$admin = $rs->current();
if ($rs->valid()) {
$_SESSION['username'] = $username;
}
}
echo ' -- session id -- ';
var_dump(session_id());
echo ' -- session var -- ';
var_dump($_SESSION);
I am using PHP5.
If you are using startlogic (seem you are ?) for your hosting, did you try doing what they say in their FAQ : http://www.startlogic.com/knowledgebase/read_article.bml?kbid=600
They indicate this :
To run PHP sessions, include the
following code at the top of any PHP
script that uses sessions:
session_save_path("your home directory
path"/cgi-bin/tmp); session_start();
Maybe this'll help ?
Especially if they are using some kind of load balancer, which balances /tmp, but not your home directory ?
If you are using a load-balanced setup, it could be that only 1 of the N servers has the correct session-data.
By default session-data is stored on the filesystem.
Per session a file is stored in /tmp/ and starts with "sess" followed by the session_id
You're absolutely positive there isn't anything ever being called prior to this? I know session_start() modifies the headers, and other than that, not sure why this isn't working.
Go ahead and turn on error reporting at the top of the script, right before the session_start() call, and see how that helps track this down:
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors',1);
session_start()

Categories