Codeigniter & PHP check if session exist - php

How can i simply check if cookies are enabled and user session too in PHP?
I need the really lighter piece of code of this world to do that, can anyone show me somenthing?
I'm on Codeigniter but i'm planning to use native PHP for this control.
my code:
if(session_start()){ echo 'started'; }
as i know Codeigniter doesn't uses native PHP session, how to do so?

Check for a valid session id:
$sid = session_id();
For example:
$sid = session_id();
if($sid) {
echo "Session exists!";
} else {
session_start();
}

The first point is "Don't fight the framework" when your framework has some functions than use it. Normally in the Framework classes are functions to prevent injections.
Here is a Post when tells you how to check the cookie:
Check if cookies are enabled
And for the session
How to tell if a session is active?

I think you can simply check by doing something like:
if(isset($_SESSION)){
// tells php session is initiated
}
if(isset($_COOKIE)){
}

Related

php $_SESSION TWIG + Mini2

I'm currently working on a new project based on Mini2 PHP framework
(here is the GitHub of the framework).
As you can see this framework use Twig, but when I want to log in people with a form, I send a request to the Model.php where I start a Session and set $_SESSION['user'] = 'John' for exemple.
The issue is that I have no idea how to check on other page is the Session has been created or even how to show the user name on a page.
Could you please help me ?
Thank you :)
try something like this:
session_start(); // start the session to have access to the session variables
if(isset($_SESSION['user'])) { // check the existance of a variable with isset()
echo "User ".$_SESSION['user']." is logged on";
}

session_start() creates new session every reload

I've read this before:
How to fix “Headers already sent” error in PHP
I have a session page, when I refresh/reload it, it creates a new session id!
<?php
$islogin=0;
$idadmin=0;
session_start();
$sid=session_id();
include("connect.php");
$result=mysql_query("select * from session_noti where sid='$sid'",$cn);
if(mysql_num_rows($result) > 0){
$row=mysql_fetch_object($result);
$islogin=$row->islogin;
$idadmin=$row->idadmin;
}else{
if(mysql_query("insert into session_noti (sid,islogin) values ('$sid',0);")){
}else{
}
}
$user_cookie=#$_COOKIE["*****"];
if($user_cookie != ''){
$user_cookie_res=mysql_query("select * from session_noti where sid='$user_cookie'");
$user_cookie_row=mysql_fetch_object($user_cookie_res);
$islogin=$user_cookie_row->islogin;
$idadmin=$user_cookie_row->idadmin;
}
?>
connect page:
<?php
$cn = mysql_connect("localhost","root","");
mysql_select_db("***");
?>
why? It works fine on localhost, when I want to upload it on server,this scenario happens.
This code seems designed very poorly. Except for the usual "PHP4-style" errors (more on that later), it doesn't really make sense to me.
If you're using PHP's sessions, why do you need to replicate a session table in your database? Y using session_start() you're already telling PHP to handle all that hassle.
Why are you accessing users' cookies directly?
I recommend that you stick with a design and follow it.
Do you want to manage sessions yourself, including passing session ids, handling cookies, etc? Then don't PHP's builtin sessions (but be careful: the possibility to write flawed code here is really high).
Do you want to use PHP's builtin sessions? Then just stick with them.
If you want to attach to each users details like "isAdmin", you can use session variables: that's what they're made for :)
<?php
session_start();
if(empty($_SESSION)) {
// Redirect to login
}
else {
if(empty($_SESSION['logged_in'])) {
// Redirect to login
}
else {
// User is logged in
// Is admin?
if(!empty($_SESSION['is_admin'])) {
// YES
}
else {
// NO
}
}
}
?>
There's plenty of guides and tutorials on using sessions with PHP. For example: http://www.phpro.org/tutorials/Introduction-To-PHP-Sessions.html
Additionally, make sure that in php.ini sessions are enabled. I strongly recommend to use "cookie_only" sessions: that is, never make PHP pass the session id as GET or POST parameter. That will screw those users with cookies disabled (are there still some?), but will save all the others from being easy targets for session hijacking.
Thus said... About your "PHP4-style" code:
Don't use mysql_* functions. They're deprecated. Use MySQLi or PDO, and use prepared statements when possible. For example, the line mysql_query("select * from session_noti where sid='$user_cookie'"); is a perfect place for an SQL Injection attack.
Don't use the # operator. It's bad! Instead, just check if the variable exists with isset() or empty().

how to implement PHP session manually

I am new to PHP. I want to implement PHP session manually. On a PHP pageload, I will check if cookie is set. If yes, I will display the required information, and if not, I will ask user to enter his details and then display the information. But I am not allowed to use PHP Sessions. I can use Cookies. Also the information needed to be displayed is about all the users (browsers) who are in session (so I have to save this to some static global array). Any help is appreciated. Thanks.
try this
setcookie('cookie_name', 'cookie_value', time());
echo $_COOKIE['cookie_name'];
Now check the cookie if it exists.
if(isset($_COOKIE['cookie_name'])) {
echo "your cookie is set";
} else {
echo "return error or any thing you want";
}
This will give you all browser(s) information.
echo $_SERVER['HTTP_USER_AGENT'];

PHP sessions working very well, but something's bugging me…

I've been working with PHP sessions, and everything is working fine it does exactly what I need.
Then I started to look into potential security issues further and found this:
http://phpsec.org/projects/guide/4.html
Notice that all that was being used was to determine existing session or new session 'status' is:
session_start();
...and yet I have seen this sort of thing many times before:
<?php
if (isset($PHPSESSID))
{
session_start($PHPSESSID);
}else{
session_start();
};
?>
I had assumed that this would allow some other processing on second call or that it's logic allowed the session to restart with the same session ID for a different page for example.
However I already thought that the plain session_start() already had logic to determine if a session had been established elsewhere because it 'knows' to retain an existing session ID rather than issuing a new one, unless it needs to of course!
So I tested the above and I couldn't get it to work at all.
<?php
if (isset($PHPSESSID))
{
$oldsession = "On";
$newsession = "Off";
session_start($PHPSESSID);
}
else
{
session_start();
$newsession = "On";
$PHPSESSID = session_id( );
};
echo 'ClientSessionID : '.$PHPSESSID.'<br>';
echo 'Refreshed Session : '.$oldsession.'<br>';
echo 'New Session : '.$newsession.'<br>';
?>
Either I'm missing something or this code could never have worked. The $oldsession NEVER gets echo'ed even though the session is retained. I conclude that the test on $PHPSESSID never works.
So my question is: Assuming the sample test code is syntactically correct, is it even plausible to attempt to pre-determine the session 'status' BEFORE calling session_start() ? And if so how would you go about it?
As the article goes on to show, using the (assumed) resulting session variables after a session has started is the only way to send the code in a different direction, so I'm thinking this is actually the only way to do it.
It looks like the article was written in early 2005, so perhaps the article was assuming that the register_globals setting was turned on. Earlier in PHP4, it was on by default, but it has been disabled by default in PHP5.
For your code to work, you'd need to explicitly use $_GET['PHPSESSID'] or $_COOKIE['PHPSESSID'], since the global variable $PHPSESSID is probably not set due to register_globals being disabled.
Also, note that the session name won't always be "PHPSESSID." That's default, but it can be changed in the session.name server setting or changed in the code at runtime with session_name().
session_start() will reclaim an active session if one exists. You can observe this behaviour with the following snippet:
<?php
session_start();
echo 'Current session ID: ' . session_id();
$_SESSION['previous_id'] = session_id();
session_regenerate_id();
echo '<br />Session ID on next execution: ' . session_id();
if(isset($_SESSION['previous_id']))
echo '<br />Session ID on previous execution: ' . $_SESSION['previous_id'];
?>
Wiseguy said the rest.
Your if(isset($PHPSESSID)) isn't checking what you think it is. I'm not sure of the syntax off hand... but try this:
<?php
if (isset(session_id($PHPSESSID)))
{
$oldsession = "On";
$newsession = "Off";
session_start($PHPSESSID);
}
else
{
session_start();
$newsession = "On";
$oldsession = "None";
$PHPSESSID = session_id( );
};
echo 'ClientSessionID : '.$PHPSESSID.'<br>';
echo 'Refreshed Session : '.$oldsession.'<br>';
echo 'New Session : '.$newsession.'<br>';
?>
I also added a value to $oldsession so that you can see that $PHPSESSID isn't 'set'.
Hope that helps!
Good luck!
Thanks Dae and Wiseguy, you answers gave me the hint I needed although what you didn't mention was the security aspect which was what brought me to the subject.
To put in context the examples I had seen undoubtedly were legacy code from a time when register_globals was switched "on" by default, and obviously had not been updated.
The reason why the code cannot work now is that regsiter_globals has been switched off as a default setting in PHP for security reasons. As of 5.3.0 it has been deprecated and I was working with 5.3.4
The security issue I was looking at was a method to determine the if the user who was using the session was the original user and not someone spoofing their session, and some of the information (IP address) could be available in the header even before you decide to start the session.
But I learn now that the IP address can also be spoofed, and therefore I think that starting the session first and (recovering any previously set session variables) validate after.
As in the original article!

Can You Switch PHP Sessions In a Session?

I have two apps that I'm trying to unify. One was written by me and another is a CMS I am using. My authentication happens in the one I coded and I'd like my CMS to know that information. The problem is that the CMS uses one session name, and my app uses another. I don't want to make them use the same one due to possible namespace conflicts but I'd still like to get this information.
Is it possible to switch session names in the middle of a request? For example, doing something like this in the CMS:
//session_start already called by cms by here
$oldSession = session_name();
session_name("SESSION_NAME_OF_MY_APP");
session_start();
//get values needed
session_name($oldSession);
session_start();
Would something like this work? I can't find anything in the docs or on the web if something like this would work after session_start() has been called. Tips?
Baring this solution, I've been considering just developing a Web Service to get the information, but obviously just getting it from the session would be preferable as that information is already available.
Thanks!
Here is a working example how to switch between sessions:
session_id('my1session');
session_start();
echo ini_get('session.name').'<br>';
echo '------------------------<br>';
$_SESSION['value'] = 'Hello world!';
echo session_id().'<br>';
echo $_SESSION['value'].'<br>';
session_write_close();
session_id('my2session');
session_start();
$_SESSION['value'] = 'Buy world!';
echo '------------------------<br>';
echo session_id().'<br>';
echo $_SESSION['value'].'<br>';
session_write_close();
session_id('my1session');
session_start();
echo '------------------------<br>';
echo $_SESSION['value'];
Log will look like:
PHPSESSID
------------------------
my1session
Hello world!
------------------------
my2session
Buy world!
------------------------
Hello world!
So, as you can see, session variables saved and restored while changing session.
Note: the answer below is not correct, please don't use or vote up. I've left it here as a place for discussion
You solution should work (not that I ever tried something like that), except that you have to manually close the previous session before any call to session_name() as otherwise it will silently fail.
You can try something like this:
session_write_close();
$oldsession = session_name("MY_OTHER_APP_SESSION");
session_start();
$varIneed = $_SESSION['var-I-need'];
session_write_close();
session_name($oldsession);
session_start;
There's no need to actually mess with the session ID value, either through PHP session ID manipulation routines or through manual cookie mangling - PHP will take care of all that itself and you shouldn't mess with that.
I've been working on perfecting this and here is what I've come up with. I switch to a parent session using session names in my child apps and then back to my child app's session. The solution creates the parent session if it does not exist.
$current_session_id = session_id();
$current_session_name = session_name();
session_write_close();
$parent_session_name = 'NameOfParentSession';
// Does parent session exist?
if (isset($_COOKIE[$parent_session_name])) {
session_id($_COOKIE[$parent_session_name]);
session_name($parent_session_name);
session_start();
} else {
session_name($parent_session_name);
session_start();
$success = session_regenerate_id(true);
}
$parent_session_id = session_id();
// Do some stuff with the parent $_SESSION
// Switch back to app's session
session_write_close();
session_id($current_session_id);
session_name($current_session_name);
session_start();
session_regenerate _id()
The manual explains this pretty well but here's some example from the manual
session_start();
$old_sessionid = session_id();
session_regenerate_id();
$new_sessionid = session_id();
echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";
print_r($_SESSION);
You should use session_id, you can use it to set / get the session id (or name).
So instead of using session_name (in your pseudo code), use session_id.
Zend_Session offers Namespacing for sessions.
Zend_Session_Namespace instances are
accessor objects for namespaced slices
of $_SESSION. The Zend_Session
component wraps the existing PHP
ext/session with an administration and
management interface, as well as
providing an API for
Zend_Session_Namespace to persist
session namespaces.
Zend_Session_Namespace provides a
standardized, object-oriented
interface for working with namespaces
persisted inside PHP's standard
session mechanism. Support exists for
both anonymous and authenticated
(e.g., "login") session namespaces.
It is possible. But I think you have to do the session handling yourself:
session_name('foo');
// start first session
session_start();
// …
// close first session
session_write_close();
session_name('bar');
// obtain session id for the second session
if (ini_get('session.use_cookies') && isset($_COOKIE[session_name()])) {
session_id($_COOKIE[session_naem()]);
} else if (ini_get('session.use_trans_sid') && !ini_get('session.use_only_cookies') && isset($_REQUEST[session_name()])) {
session_id($_REQUEST[session_naem()]);
}
// start second session
session_start();
// …
But note that you might do some of the other session handling things like cookie setting as well. I don’t know if PHP does this in this case too.

Categories