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()
Related
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
I had a login system set up that stored a session variable and checked it on each page, but then I moved to a new server.
Now any session variable I set is only available on the page it was set on. I've been searching for reasons why this could happen, and already crossed off permissions issues. Is it possible this has to do with incorrect urls? Everything else on the server appears to be working fine.
I'm running the latest version of PHP and Apache if that helps at all.
Because you probably (just assumption) have not got session_start(); throughout your other pages where required. So for example, create a page called session.php
Session.php
session_start();
if (!isset($_SESSION))
{
// Enforce logout as session is not set.
}
then:
include "session.php";
use this snippet through out your pages where your login features are required.
I've run into issues like this before. You might try setting a session id when you first start the session using session_id(), and then use the same session id before each session_start().
For example:
<?php
session_id(integer);
session_start();
?>
I am working with a PHP Login System from http://tutorialzine.com/2009/10/cool-login-system-php-jquery/ Just to give you a quick overview, I believe the tutorial sets up the variable in the following manner:
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('tzLogin');
// Starting the session
session_set_cookie_params(1*7*24*60*60);
// Making the cookie live for 1 weeks
session_start();
if($_SESSION['id'] && !isset($_COOKIE['tzRemember']) && !$_SESSION['rememberMe'])
..........
So far so good, except that I cannot carry over the session variables from the Main Login page to subsequent pages (which contain restricted content). Here is the basic code that I intend to place at the start of each restricted content page
<?php
session_name('tzLogin');
session_set_cookie_params(1*7*24*60*60);
session_start();
if($_SESSION['id']) <-- I believe I need more code here (incldue the cookie)
{
//If all is well, I want the script to proceed and display the HTML content below.
}
else
{
header("Location: MainLogin.html");
or die;
//redirects user to the main login page.
}
?>
As you can see, I am a total novice, but any help would be greatly appreciated. As of now, my restricted content pages keep getting redirected to the homepage even when I am properly logged in. Hence I suspect, the SESSION state is not being carried over. Thanks again!
You should probably make sure that you set the path and domain when you invoke session_set_cookie_params:
session_set_cookie_params ( 1*7*24*60*60, '/','.yourdomain.com')
See http://php.net/manual/en/function.session-set-cookie-params.php
(It's a good idea to set the httpOnly attribute as well.)
Additionally, make sure you actually assign some value to your session id key (it's not clear in your code sample that you do):
$_SESSION['id'] = 'some value';
Finally, you may want to use session_status() while debugging to verify you've actually started the session correctly (http://php.net/manual/en/function.session-status.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.
I have a PHP authentication system on my website using the $_SESSION variable.
A form submits a username and password to the file "login.php". It is handled like this:
<?php include '../includes/sessionstart.inc.php'; ?>
<?php ob_start(); ?>
if($_POST){
$q = mysql_query("SELECT id, company FROM users WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".md5($_POST['password'])."'");
if(mysql_num_rows($q) >= 1){
$f = mysql_fetch_Array($q);
$_SESSION['company'] = $f['company'];
$_SESSION['id'] = $f['id'];
$_SESSION['logedin'] = true;
session_write_close();
ob_clean();
header("Location: index.php");
}
Afterwards, index.php is loaded and checks whether 'logedin' is true.
<?php include '../includes/sessionstart.inc.php'; ?>
<?php if(!isset($_SESSION['logedin'])) header('Location: login.php'); ?>
On my production server, it continues, but on my Wampserver, it reverts back to login.php. I notice that Wampserver is very slow in page loading, this might have to do something with it. That's why I included the session_write_close, to make sure session data is saved before the pages are switched, but it doesn't help.
The contents of session_start.inc.php are simply:
<?php
session_start();
?>
I used to have more code in there, but at the moment it's just this. The problem also existed before I started using an include file.
Does anybody have an idea what I'm doing wrong? Why doesn't Wampserver transmit my SESSION data to the next PHP file?
WAMP server 2 - settings are not set by default for $_SESSION var.
PHP.ini
requires the following settings
C:\wamp\bin\apache\apache2.4.2\bin\php.ini
session.cookie_domain =
session.use_cookies = 1
session.save_path = "c:\wamp\tmp" ;ensure the \ is used not /
Session testing -
load.php -- load $_SESSION var.
<?PHP
session_start();
$_SESSION['SESS_MEMBER_ID'] = 'stored variable';
session_write_close();
header("location:print.php");
?>
print.php -- print $_SESSION var.
<?PHP
session_start();
var_dump($_SESSION);
?>
run the script in your browser var_dump() should produce results
go to c:\wamp\tmp Files containing the session data will appear here.
First of all: the index logedin seems strange for keeping track of a user being logged in. Is this just a typo on SO, or really a code-typo?
Second (depending on the desired behavior), try another approach for making pages login-protected. Your page should look something like
<?php
include 'login.inc.php';
if(authorized()) {
// put some more script here, if needed
?>
// put some plain HTML here
<?php
}
?>
Where login.inc.php handles the session, cookies. In particular, the authorized function should return TRUE if a client is already logged in. If a client is not logged in, it should display a form with action $_SERVER['PHP_SELF'] and return FALSE. If you name the submit-input something like login_submit, you can let login.inc.php handle the verification.
This way, you don't need to refer users to a dedicated login page, and after logging in, user are directly shown the requested page. You can tweak this a bit to make query-strings persistent through login as well.
Try to replace
if($_POST){...}
with
if( isset($_POST['username']) && isset($_POST['password']) ){...}
... at least for debugging purposes. It's possible that some different settings are causing a non-empty $_POST array where it's not expected.
Also, your code seems to be missing exit() calls after header() redirections. Sending an HTTP Location header doesn't automatically stop your script.
I had this problem using WAMPSERVER for development on /localhost. I needed to change session.use_only_cookies either in-line or in the php.ini setting from
session.use_only_cookies = 1
to
session.use_only_cookies = 0
Explanation
Using default cookie-based sessions was working as expected but I needed a cookie-less solution. A test starting page:
<?php
// page1.php
ini_set('session.use_cookies', '0');
session_start();
$_SESSION['time'] = time();
echo '<br />page 2';
?>
The session data was created and stored successfully in the WAMPSERVER temp directory, e.g., C:\wamp\tmp\sess_0rkdlonl5uia717rf03d4svs16. The link generated by the above code looks similar to (note the UID matches the session data file name):
page2.php?PHPSESSID=0rkdlonl5uia717rf03d4svs16
But the destination page2.php was throwing undefined errors for the variable 'time' whilst attempting to retrieve the session data:
<?php
// page2.php
ini_set('session.use_cookies', '0');
session_start();
echo date('Y m d H:i:s', $_SESSION['time']);
echo '<br />page 1';
?>
By setting session.use_only_cookies FALSE in either the script before session_start();:
ini_set('session.use_only_cookies', '0');
or changing it globally in php.ini:
; This option forces PHP to fetch and use a cookie for storing and maintaining
; the session id. We encourage this operation as it's very helpful in combatting
; session hijacking when not specifying and managing your own session id. It is
; not the end all be all of session hijacking defense, but it's a good start.
; http://php.net/session.use-only-cookies
session.use_only_cookies = 0
solved the problem.
After a long time I have fixed this bug finally.
On my localhost WAMP, the session data is not saved between page loads, because the session data is stored in a cookie, and there is no cookie domain to be set for localhost.
The solution:
'session.cookie_domain' should be set to empty string for all local domain names, not only for 'localhost' (but should not be empty for local IP addresses):
<?php
ini_set('session.cookie_domain', (strpos($_SERVER['HTTP_HOST'],'.') !== false) ? $_SERVER['HTTP_HOST'] : '');
?>
Thanks to Marcin Wiazowski who posted it here.
Faced the same problem but it was being caused by
session_regenerate_id(true);
So I just deleted it from my code.
Update to WAMP 2.5 and now the problem is solved!