got a (I guess...) very simple problem:
I want to set a session within a function.
Simple situation:
I got a login form. After subimitting the form, I call a function "login" which checks if user has authenticated. If yes, a session should be set.
Here some very simple code:
session_start();
function login() {
$SESSION['login'] = true;
}
if (isset($_REQUEST['doLogin'])) {
login();
// is session is set here, it works...
}
if ($SESSION['login'] === true) echo 'you are logged in';
But this doesn't work. Why?
Thanks alot!
You are using $SESSION you need to be using $_SESSION
Related
I can log in and access all member pages, but when I log out, I can still access all memberspages
I use this code to log out:
$_SESSION["admin_id"] = false;
$_SESSION["username"] = null;
redirect_to("login.php");
and this code to check if a user is logged in,
function logged_in() {
return isset($_SESSION["admin_id"]);
}
function confirm_logged_in($page) {
if (!logged_in()) {
redirect_to($page);
}
}
he redirects me after i have used the log out code. But i can still type in the member page URL and access them like I am logged in. I use an other webbrowser its impossible, so the pages are protected correctly. Or do I need to destroy the cookie and session complectly?
Here's what you're doing when you logout.
You are setting admin_id to false (which is technically a value).
$_SESSION["admin_id"] = false;
You then check to see whether admin_id is set:
isset($_SESSION['admin_id'); // returns TRUE because it "IS SET" to false
Options
You can either check whether admin_id is not empty (which handles null, false, 0).
function logged_in() {
return ! empty($_SESSION["admin_id"]);
}
You can extend your current function.
function logged_in() {
return isset($_SESSION["admin_id"] && $_SESSION["admin_id"] !== false);
}
You can set the variable to null.
$_SESSION['admin_id'] = null;
You can destroy the session completely.
session_destroy();
In place of:
$_SESSION["admin_id"] = false;
Try this:
unset($_SESSION["admin_id"]);
If you really need to log out, in my opinion your best option is to invalidate the session with a simple session_destroy().
By doing this you can check $_SESSION with the isset() function without problems, since every parameter belonging to the old session has been unset.
I am facing a very strange problem , i am doing CasLogin in my application..
i have successfully implemented CAS, i.e all values are set in $_SESSION variable after all proper validations, and successful login, but when i redirect it from CasLogin() action to Index Action $_SESSION contains nothing..
i am using Yii Frame Work.
here is code.
public function actionCasLogin($CID=NULL)
{
//code to be imported from GMS here
PhpCasControl::setPhpCasContext($CID);
phpCAS::setPostAuthenticateCallback(array($this,'_saveServiceTkt'));
$loginForm = new CasLoginForm;
// validate user input and redirect to the previous page if valid
if ($loginForm->login($CID)) {
if (Yii::app()->user->isGuest){
echo '<br> <br> This shows up..';
var_dump($_SESSION);
}
else{
echo 'Hello at caslogin <br>never shows up';
var_dump(Yii::app()->user->id);
}
$this->redirect(array('index'));
}
else {
throw new Exception("You don't have sufficient permissions to access this service. Please contact Administrator !");
}
}
this function Works Properly and if i put a EXIT; here it will display $_SESSION with all the desired values..
but after redirection... to index..
whose code is this..
public function actionIndex()
{
echo"hello at index";
if (! Yii::app()->user->isGuest) {
//#CASE 1: User is already logged in
$this->redirect(array("site/upload"));
}
else{
//#CASE 2: User is not Logged in
echo '<br>shows up with empty session<br>';
var_dump($_SESSION);
var_dump(Yii::getVersion());
exit;
$this->redirect(array("site/login"));
}
}
here $_SESSION is empty..
any explanation why this might be happening..
i am aware of CAS creating its own session by service ticket name.. i have handled that thing.. by RenameSession function, which i call in CasLoginForm..
whose code is this..
public function rename_session($newSessionId) {
//Store current session variables so that can be used later
$old_session = $_SESSION;
//Destroy current session
session_destroy();
// set up a new session, of name based on the ticket
$session_id = preg_replace('/[^a-zA-Z0-9\-]/', '', $newSessionId);
//start session with session ID as 1) service ticket in case of CAS login, 2) random sTring in case of local login.
session_id($session_id);
session_start();
//echo "<br>new session <br>";
//Restore old session variables
$_SESSION = $old_session;
//var_dump($_SESSION);
}
OK, i think that you should use session_id to change the id.
public function rename_session($newSessionId) {
// set up a new session id, of name based on the ticket
session_id(preg_replace('/[^a-zA-Z0-9\-]/', '', $newSessionId));
}
I'm trying to implement and authentication system with jQuery and PHP. All the php work is made in the controller and datahandler class. There is no php code inside the .html files, all the values in .html files are rendered via jQuery that request the data from php server. So what I'm trying to do is:
When user clicks the login button, the jQuery makes a call to the authenticate() method in my controller class, it checks if the user is correct and stuff, and if it is, start the session and set the user_id on the session so I can access it later, and returns the userId to the jQuery client again.
After that, if everything is fine, in jQuery I redirect it to the html file. On the html file I call a jQuery from the <script> tag that will handle other permissions. But this jQuery will access the method getPermissionString (from the same class of authenticate() method mentioned before), and it will need to get the session value set in authenticate method.
The Problem:
When I try to get the session value inside getPermissionString() it says:
Notice: Undefined variable: _SESSION
I've tried to check if the session is registered in the second method, but looks like it's not. Here is my PHP code.
Any idea? Thanks.
public function authenticate($login, $password)
{
$result = $this->userDataHandler->authenticateUser($login, $password);
if(is_numeric($result) && $result != 0)
{
session_start();
$_SESSION["uid"] = $result;
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
echo $result;
}
else
{
echo 0;
}
}
public function getPermissionString()
{
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
}
Before you can access $_SESSION in the second function you need to ensure that the program has called session_start() beforehand. The global variable is only populated when the session has been activated. If you never remember to start a session before using it then you can change the php.ini variable below:
[session]
session.auto_start = 1
Further, you said that you're using a class for your code. In this case you can also autos tart your session each time the class in created by using magic methods:
class auth {
function __construct() {
session_start();
}
function yourfunction() {
...
}
function yoursecondfunction(){
...
}
}
If you don't have session.auto_start enabled, and authenticate and getPermissionString are called on two different requests, you need to call session_start() in each function.
If you need more information on how the session ID is passed, just read Passing the Session ID
You should not use that function if session is not started. So throw an exception:
public function getPermissionString()
{
if (session_status() !== PHP_SESSION_ACTIVE)
{
throw new Exception('No active session found.');
}
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
}
This ensures the pre-conditions of your functions are checked inside the function so you don't need to check it each time before calling the function.
You will now see an exception if you wrongly use that function and it will give you a backtrace so you can more easily analyze your code.
For php sessions to work you have to call session_start() every time you script is requested by the browser.
Is this function good for a quick login function with only one user?
function auth($post, $session)
{
if(isset($post["username"]) && isset($post["password"]))
{
$session["user"] = new stdClass();
$session["user"]->username = $post["username"];
$session["user"]->password = $post["password"];
}
if(isset($session["user"]))
if(is_object($session["user"]))
if($session["user"]->username == "admin" && $session["user"]->password == "test")
return true;
return false;
}
It works but, must it be improved?
Use the session to track whether the user is logged in or not. For example, in the login page, only set the username in the session if the user authenticates properly. Logout page clears it. Then your other pages can check if the username is set in the session or not. No need to store entered password (recommend against).
Ok, having trouble here:
I created a login script, so after a person logs in then they will get direted to another page. And also, I have it redirecting them to the login page if they try and access one of those other pages.
My problem is, if a user is logged in and stumbles to the login page again --by accident-- I would like for it to recognize that the user is logged in and redirect them to that next page (which is index2.php) ?? Having troubles :-(
Here is my code so far:
require_once "inc/functions.class.php";
$quickprotect = new functions('inc/ini.php');
if (isset($_SESSION['goAfterLogin'])){
$goto = $_SESSION['goAfterLogin'];
unset($_SESSION['goAfterLogin']);
}
else $goto = $quickprotect->settings['DEFAULT_LOGIN_SUCCESS_PAGE'];
if (isset($_POST[username])) {
if($quickprotect->login($_POST[username], $_POST[password])) header ("Location: $goto");
}
Here is how I store a users session in the functions page
public function is_logged_in() {
//Determines if a user is logged in or not. Returns true or false;
if ($_SESSION['logged_in'] === md5($this->settings[ADMIN_PW])) {
return true;
}
else return false;
}
You don't mention how you store your users in your session, but something like this should do it for you:
if(isset($_SESSION['user']))
{
header("Location: index2.php");
exit;
}
This will check if you have a user in your session, and if so, redirect to index2.php.
You need to change 'user' according to your session key.