I created a system that sends the user id by Unity3D and on the server creates a session and sends the session back to the client (on Unity3D), so it all works! But when I send back from Unity3D to the server the session is simply gone! I already checked the browser and it works, it just does not work on Unity3D!
Does anyone have any idea what it is?
C# on Unity3d
void Start () {
WWW w = new WWW (url+ "?id=" + userId);
StartCoroutine (SessionWWW (w));
}
private IEnumerator SessionWWW (WWW _w){
yield return _w;
PlayerPrefs.SetString("cookie", _w.text);
Debug.Log (PlayerPrefs.GetString("cookie"));
Debug.Log (_w.text);
}
void Update(){
if (Input.GetKeyDown (KeyCode.P)) {
string session= PlayerPrefs.GetString("cookie");
WWW w = new WWW (url "?sessionid=" + session);
StartCoroutine (GetSessionWWW (w));
}
}
private IEnumerator GetSessionWWW (WWW _w){
yield return _w;
if (_w.text == "ok") {
Debug.Log ("received!");
} else {
Debug.Log (_w.text);
}
}
PHP script:
<?PHP
session_start();
if(isset($_GET['id'])){
$id = $_GET['id'];
$_SESSION['session'] = $id;
echo $_SESSION['session'];
}
if(isset($_GET['sessionid'])){
if(isset($_SESSION['session'])){
echo $_SESSION['session'];
}
}
?>
If your wanting to set the session id of the current session in PHP use the function session_id($id) BEFORE session_start.
https://www.php.net/manual/en/function.session-id.php
<?php
//do you need both of these?
if(isset($_GET['id'])){
$id = $_GET['id'];
session_id($id);
}
if(isset($_GET['sessionid'])){
$sessionid = $_GET['sessionid'];
session_id($sessionid);
}
session_start();
print_r($_SESSION)
?>
session_id ([ string $id ] ) : string
If id is specified, it will
replace the current session id. session_id() needs to be called before
session_start() for that purpose. Depending on the session handler,
not all characters are allowed within the session id. For example, the
file session handler only allows characters in the range a-z A-Z 0-9 ,
(comma) and - (minus)
you might also want to validate before setting the session id to prevent mistakes from your code and if this is on the internet other people can find it too.
(from the link above)
function session_valid_id($session_id)
{
return preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $session_id) > 0;
}
$id = $_GET['id'];
if (session_valid_id($id)) {
session_id($id);
}
Related
I am working using cookie. My client wants when a visitor visits his site, it will be automatically checked that he visited this site before.If he visited this site before, he will be auto redirected the site he visited before. If he doesn't visited this site before, cookie will be saved that if he will visited this site in future, he will be redirected his last visited page. For example, A site has many category or topic such as Food, Cloth etc. If a visitor visits this site in Cloth topic or category, cookie will be saved. Next time he visits this site, he will be automatically redirected cloth category page cause in past, he visited that page. But this time, a option in footer to save cookie again and if he click to accept cookie, cookie will be saved updated.
Now i am trying to do this in localhost and shared it's file. Please check what's the problem or where. Here i use redirect option in header.php and face problem. If i use redirect option in index.php, error occurs ( see screenshot). If i use in header.php, error occurs in every page. See screenshot: http://prntscr.com/cbkux6
You can visit this site for an example: http://www.louisvuitton.com/
my header page
<?php
if(isset($_COOKIE['saveexperice'])){
$link = $_COOKIE['saveexperice'];
header("Location: $link");
exit;
}
else{
header('Location: http://localhost/cookie');
$exlink = $_SERVER['PHP_SELF'];
setcookie('saveexperice', $exlink, time()+60*60*24*30);
exit;
}
My Index page
<?php
include("header.php");
//$page_link = $_SERVER['PHP_SELF'];
echo "Index page";
//echo $page_link;
print_r($_COOKIE);
include("footer.php");
footer page
Logout
Another page
<?php
include("header.php");
print_r($_COOKIE);
echo "Ex php page";
include("footer.php");
cookie clear page
<?php
$exlink = $_SERVER['PHP_SELF'];
setcookie('saveexperice', $exlink, time()-60*60*24*30);
header('location: index.php');
another page
<?php
include("header.php");
print_r($_COOKIE);
echo "CK php page";
include("footer.php");
You can download this full project zip file
http://www116.zippyshare.com/d/6Gz32nO0/2541183/Coockie.zip
As I mentioned in my comment, incase I wasn't clear, you don't have any stop code so either way, you will redirect. You have no condition where you will not redirect:
<?php
// Move here
$exlink = $_SERVER['PHP_SELF'];
if(isset($_COOKIE['saveexperice'])){
$link = $_COOKIE['saveexperice'];
// If your cookie doesn't match where you are now
if($exlink != $link) {
// Redirect
// NOTE: You may want to check the timestamp and only redirect
// if the cookie is X-amount of minutes old otherwise you
// will probably be stuck in another loop, always pushing you
// to the same page.
// If it's within the timeframe to not push to another page,
// then you have to reset the cookie to the current page.
header("Location: {$link}");
exit;
}
}
else{
setcookie('saveexperice', $exlink, time()+60*60*24*30);
// I am not sure why you need to redirect here since you are on a page
// you supposedly want to be on
header('Location: http://localhost/cookie');
exit;
}
EDIT:
Alright, so since you can not get my edit to work, I have added another layer to this to add some human-readable methods so the code is more understandable. IT is a quick class that you can build on, but all the methods are pretty self-explanatory. It's parts (in general) from one I use:
<?php
# I am calling it Session, but that is because it would have both cookie and session methods
class Session
{
private $expireTime,
$cookieName;
/*
** #description This will set the time for the cookie to expire
*/
public function setTime($time)
{
$this->expireTime = $time;
return $this;
}
/*
** #description Returns the name of the last cookie used in the instance
*/
public function getName()
{
return $this->cookieName;
}
/*
** #description This will set the name of the cookie
*/
public function setName($name = false)
{
$this->cookieName = $name;
return $this;
}
/*
** #description This actually creates the cookie
*/
public function setCookie($val, $name = false)
{
if(!empty($name))
$this->setName($name);
if(empty($this->cookieName))
return false;
$this->expireTime = (!empty($this->expireTime))? $this->expireTime : (time()+60*60*24*30);
setcookie($this->cookieName,json_encode(array($this->expireTime,$val)),$this->expireTime);
}
/*
** #description Self-explanatory
*/
public function destroyCookie($name = false)
{
if(!empty($name))
$this->setName($name);
if($this->cookieExists($this->cookieName))
setcookie($this->cookieName,null,(time()-1000));
}
/*
** #description Self-explanatory
*/
public function cookieExists($name = false)
{
if(!empty($name))
$this->setName($name);
return (isset($_COOKIE[$this->cookieName]));
}
/*
** #description Self-explanatory
*/
public function getCookie($name = false)
{
$cookie = $this->getCookieData($name);
return (!empty($cookie[1]))? $cookie[1] : $cookie;
}
/*
** #description This will get an array of the value and expire time
*/
public function getCookieData($name = false)
{
if(!empty($name))
$this->setName($name);
return (!empty($_COOKIE[$this->cookieName]))? json_decode($_COOKIE[$this->cookieName],true) : false;
}
/*
** #description Checks if the cookie is expired
*/
public function isExpired($name = false)
{
$cookie = $this->getCookieData($name);
if(!empty($cookie[0]))
return false;
return true;
}
/*
** #description Gives an array for a countdown of sorts
*/
public function willExpire($name = false)
{
$cookie = $this->getCookieData($name);
$now = strtotime("now");
if(!empty($cookie[0])) {
$seconds = ($now - $cookie[0]);
return array(
'h'=>trim(number_format(($seconds/60/60),0),'-'),
'm'=>trim(number_format(($seconds/60),0),'-'),
's'=>trim($seconds,'-')
);
}
return true;
}
/*
** #description Resets the expire time on the cookie
*/
public function extendTime($time,$name=false)
{
$cookie = $this->getCookieData($name);
$this->setTime($time)->setCookie($cookie[1]);
}
}
To use:
<?php
# Add the class
require_once(__DIR__.'/Session.php');
# Create instance
$cEngine = new Session();
# Check if the cookie exists already
if(!$cEngine->cookieExists('saveexperice')) {
# If it doesn't exist, create it by
# First setting an expire time
$cEngine->setTime(strtotime('now + 20 minutes'))
# Add the data
->setCookie($_SERVER['PHP_SELF'],'saveexperice');
}
# This would just echo the value
echo $cEngine->getCookie();
# This will tell you when it will expire (count down)
print_r($cEngine->willExpire());
# This will extend the expiration time on the cookie
$cEngine->extendTime(strtotime("now + 1 day"));
# This will destroy the cookie
# $cEngine->destroyCookie();
I am having problems with the session_id() that returns a new value every time on browser refresh/restart.
Read this post here but it doesn't solve the issue.I did all that was mentioned there - browser accepts cookies, permissions are set correctly, no param value is changed on sequential requests, etc.
Could this be refered to not using the session_name() or session_set_cookie_params() correctly? Or maybe it is the initial configuration that should be fine-tuned?
public static function init_session($name = FALSE, $lifetime = 10, $path = '/', $domain = FALSE, $secure = FALSE)
{
if (empty($name))
{
$name = APP_NAME;
}
if (empty($domain))
{
$domain = BASE_URL;
}
session_name($name);
session_set_cookie_params($lifetime, $path, $domain, $secure, TRUE);
session_start();
echo session_id();
}
First of all, you set your session lifetime to 10 seconds, which means that you get a new session after every 10 seconds.
Side note: It's normal behaviour for some browsers to discard session cookies when closing the browser.
If you need your session to expand over multiple browser sessions, you need to use persistent cookies.
Example:
function init_session(/* ... */)
{
if(!isset($_SESSION)) {
session_start();
}
//Is it a running session?
if(isset($_SESSION['somevalue'])) {
//Everything is fine, session is loaded, no need to reload from cookies
} else {
if(isset($_COOKIE['yourcookiename'])) {
//reload session from cookie
} else {
create_session();
}
}
}
function create_session()
{
$_SESSION['somevalue'] = 1;
//setcookie
}
Read http://www.allaboutcookies.org/cookies/cookies-the-same.html
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 writing a simple website which allows a user to login, fill out a form which is submitted to a database and then log out. In order to manage the session, I used the session manager which is described by TreeHouse on the following page: http://blog.teamtreehouse.com/how-to-create-bulletproof-sessions
In order to protect against hijacking, the client's IP address and user agent are stored in the session variable and compared to the server's values for these properties on each page. If they don't match, then it is assumed that the session has been hijacked and it is reset.
The implementation seems to work on my local machine without any issues, but when I uploaded it to the server, each page refresh causes the preventHijacking() function to return false (meaning it believes the session has been hijacked). However, if I echo any text within that function, the problem mysteriously disappears and the whole thing works as I expect it to (except for the bit of echoed text which is now displayed above my form :P).
I haven't a clue why this would be the case and I can't figure out how to fix it. The session manager code is below. At the start of each page, I use this to start the session and then each page simply uses or sets whatever variables it requires. If anyone could suggest why the function always returns false unless it echoes text and perhaps suggest what modification I need to make so that it will behave in the expected manner, I'd really appreciate it.
<?php
class SessionManager {
protected static $timeout = 600; // Time before automatic logout for the session
static function sessionStart($name, $limit=0, $path='/', $domain=null, $secure=null) {
// Set the cookie name before we start
session_name($name.'_Session');
// Set the domain to default to the current domain
$domain = isset($domain)? $domain : $_SERVER['SERVER_NAME'];
// Set the default secure value to whether the site is being accessed with SSL
$https = isset($secure)? $secure : isset($_SERVER['HTTPS']);
// Set the cookie settings and start the session
session_set_cookie_params($limit, $path, $domain, $secure, True);
session_start();
// Make sure the session hasn't expired and destroy it if it has
if(self::validateSession()) {
// Check to see if the session is new or a hijacking attempt
if(!self::preventHijacking()) {
// Reset session data and regenerate ID
$_SESSION=array();
$_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
self::regenerateSession();
// Give a 5% chance of the session ID changing on any request
} else if (rand(1, 100) <= 5) {
self::regenerateSession();
}
$_SESSION['LAST_ACTIVITY'] = time();
} else {
$_SESSION = array();
session_destroy();
session_start();
}
}
static function preventHijacking() {
if(!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent'])) {
return false;
}
if($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR']) {
return false;
}
if($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']) {
return false;
}
return true;
}
static function regenerateSession() {
// If this session is obsolete, it means that there already is a new id
if(isset($_SESSION['OBSOLETE']) && $_SESSION['OBSOLETE'] === True) {
return;
}
// Set current session to expire in 10 seconds
$_SESSION['OBSOLETE'] = True;
$_SESSION['EXPIRES'] = time() + 10;
// Create new session without destroying the old one
session_regenerate_id(false);
// Grab current session ID and close both sessions to allow other scripts to use them
$newSession = session_id();
session_write_close();
// Set session ID to the new one and start it back up again
session_id($newSession);
session_start();
// Now we unset the obsolete and expiration values for the session we want to keep
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}
static protected function validateSession() {
// Check if something went wrong
if(isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES'])) {
return false;
}
// Test if this is an old session which has expired
if(isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time()) {
return false;
}
// Check if the user's login has timed out
if(isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > self::$timeout) {
return false;
}
return true;
}
}
?>
I could be way out here (it's been a while) but that sounds like the buffer containing the headers isn't being flushed for some reason. Providing body would force them to be flushed, so maybe not providing the body doesn't flush?
Try putting ob_end_flush(); in there before you return. That may fix it.
Is it secure to use
If ($_SESSION['authenticated'] == true) {
/////Show secure page
}
Can someone just go and change where the session variable is stored to make their $_SESSION['autheticated'] = to true?
Same thing with a user having $_SESSION['id'] = to their index id. How would I be able to make this securer?
Could someone just go and change the id value and impersonate another user?
Would the below method be the right way to make something securer?
$_SESSION['random_check'] = (random number)
and also store this in a column in my database and each time I would
If ($_SESSION['authenticated'] == true && $_SESSION['random_check'] == random_number ) {
/////Then show secure page
}
Thanks,
I'm pretty sure Session in most hosting is just an interface to your filesystem, i.e. all Session data is stored in the server's hard disk, if you look at phpinfo() output, you can have a look at where the actual path of Session data is.
With that said, unless you chmod your session path to 777 and the attacker happens to know where you are hosting your app and has the login, then I don't think it's much of an issue.
The bigger issue here is securing your cookie as it's the piece of information that's going back and forth through your server and client, which attackers can use to impersonate legit users.
Yes,Is it secure to use. I use this.
I do this:
-check login,if is an valid login , set $_SESSION['logged'] = 'yes' and generate um token $_SESSION['token'] = 'the token'
this token, I save in an input html element and check in each action.
something like:
<?php
class token {
public function generateToken() {
return $_SESSION['token'] = md5( microtime() );
}
function generateField($name = "token"){
return "<input type='hidden' value='{$_SESSION['token']}' name='{$name}'>";
}
public function getToken() {
return $_SESSION['token'];
}
public function getTokenFromFields($method = "GET") {
return strtoupper($method) == "GET" ? $_GET['token'] : $_POST['token'];
}
public function checkToken() {
return $this -> getToken() == $this -> getTokenFromFields();
}
public function updateToken() {
$_SESSION['token'] = md5( microtime() );
}
}
?>
<?php
//orther file
require 'class.token.php';
$token = new token();
$Atoken = $token -> generateToken();
echo "<script>
var data = {};
data['token'] = '{$Atoken}';
data['foo'] = 'baa';
</script>";
$token -> generateField();
?>
<script>
$.ajax({type:"GET", url:"process.php", "data=foo=baa&token=" + data.token, success:function(response) { } })
</script>
In process.php:
<?php
if($_SESSION['token'] == $_GET['token']) {
//do something
} else die('bad token');
?>