会话在每个请求上重新生成,如何在每个请求上获得相同的会话

时间:2017-05-10 09:44:30

标签: php .htaccess session cookies

当我将会话重写为类时 - 会话在每个请求上重新生成。 (此外,我添加了params到cookies,但现在我禁用了它们。)

我有一个会话,作为一个包含文件,我没有给cookie添加任何参数。它工作正常。

我只在localhost上试试。

我的路径不标准 - 我使用一种MVC和.htaccess文件将url转换为Controller,Action和Parameters。

的.htaccess     选项-MultiViews     选项 - 索引

.com

这意味着来自Options +FollowSymlinks RewriteEngine on RewriteBase /public/ IndexIgnore * RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteCond %{ENV:REQUEST_FILENAME} !-d RewriteCond %{ENV:REQUEST_FILENAME} !-f RewriteCond %{ENV:REQUEST_FILENAME} !-l RewriteRule ^index.php?(.+)$ index.php?url=$1 [QSA,L] 将被提取www.domain/public/index.php/controllerName/actionName/parameters

我的课程班级:

$_REQUEST['url'] = controllerName/actionName/parameters

在讨论会议时,我得到以下内容:

1)在函数ownDealSession中,我回显“462 ownDealSession,_SESSION =”;的print_r($ _ SESSION);

<?php namespace nms; use Bundle\SecureC\secureTr; //generates random string class SessionClass { use secureTr; private $action; //current action private $path; //current path private $title; private $msgsessEnd; //part of OauthSession entity private $sessName; //session name is the variable in the cookie //The session name is reset to the default value stored in session.name at request startup time. //Thus, you need to call session_name() for every request (and before session_start() //or session_register() are called). private $timelimit; private $domain; private $securePath; private $ifhttps; private $ifhttponly; private $sesdata; private $sesDataArr; private $sessCount; private $salt; private $sesskey; private $redirToken; private $sessLooseIp; private $sessLooseAgent; private $sessProxyIp; private $sessStart; private $sessLastRestart; private $sessEnd; private $serverAddrArr; public function __construct($sessArr=[]) { $this->serverAddrArr = []; $this->serverAddrArr [] = $_SERVER['SERVER_ADDR']; $this->serverName = []; $this->serverName[] = $_SERVER['SERVER_NAME']; $status = session_status(); //PHP_SESSION_DISABLED - 0 if sessions are disabled. //PHP_SESSION_NONE - 1 if sessions are enabled, but none exists. //PHP_SESSION_ACTIVE -2 if sessions are enabled, and one exists. echo "<br><br> 96 Sessiong.php constructor status =". $status; if( $status== 'PHP_SESSION_ACTIVE' || $status==2 ) { $this->sessId = session_id(); } else { $this->sessId = false; } $this->timelimit = !empty($sessArr['timelimit']) ? $sessArr['timelimit'] : SESSION_TIMELIMIT; $this->domain = !empty($sessArr['domain']) ? $sessArr['domain'] : $_SERVER['HTTP_HOST']; // if(empty($domain)) { $domain = $_SERVER['SERVER_NAME']; } if(empty($domain)) { $domain = DOMAIN_wwwNAME; } $this->path = !empty($sessArr['curPath']) ? PREP.$sessArr['curPath'] : COOKIE_PATH; $this->ifhttps = (HTT == 'https://') ? true : isset($_SERVER['HTTPS']); $this->ifhttps = isset($sessArr['ifhttps']) ? $sessArr['ifhttps'] : $this->ifhttps; $this->ifhttponly = isset($sessArr['ifhttponly']) ? $sessArr['ifhttponly'] : COOKIE_HTTPONLY; $this->sessLooseIp = long2ip(ip2long($_SERVER['REMOTE_ADDR']) & ip2long("255.255.0.0")); //check the beginning of string, because end may change, depending on device rotation on mobile and iPad $this->sessLooseAgent = substr($_SERVER['HTTP_USER_AGENT'],0,25); //$redirToken = md5( uniqid(microtime(), true) ); //$this->redirToken = 'rt_**_'. $redirToken .'_**_'. $this->genRandomStr(8); $this->data = isset($sessArr['data']) ? $sessArr['data'] : []; //data here is vdArr; //these are used for custom sessions, like payment session //tile - payment //msgsessEnd - Please start the payment from the beginning, because of long inactivity your data was lost. //you also can provide another timelimit $this->title = isset($sessArr['title']) ? $sessArr['title'] :""; //data here is vdArr; $this->msgsessEnd = isset($sessArr['msgsessEnd']) ? $sessArr['msgsessEnd'] : 'After longer inactivity time you was log-out. Please login to continue'; //data here is vdArr; $this->ownDealSession(); //starts if needed } //not filly finished, because my application use javascript public function checkCookiesEnabled ($givArr) { setcookie("test_cookie", "test", time() + 3600, '/'); $actionName = isset($givArr['actionName']) ? $givArr['actionName'] : $this->htt->safeRedirct('security/checkcookie', true, true, [ 'cururl'=> $actionName ] ); } public function ownSetCookieParams() { if( $this->ifhttponly) { ini_set("session.cookie_httponly", 1); $params = session_get_cookie_params(); //echo "<br><br> 21 params after ini_set ="; print_r($params); } //Set cookie parameters defined in the php.ini file. //The effect of this function only lasts for the duration of the script. //Thus, you need to call session_set_cookie_params() //for every request and before session_start() is called. // Set the default secure value to whether the site is being accessed with SSL session_set_cookie_params( $this->timelimit, $this->path, $this->domain, $this->ifhttps, $this->ifhttponly ); $params = session_get_cookie_params(); echo "<br><br> 21 Sessiong, cookie params after session_set_cookie_params ="; print_r($params); // session_set_cookie_params ( int $lifetime // [, string $path [, string $domain [, // bool $secure = false - If TRUE cookie will only be sent over secure connections. // [, bool $httponly = false - PHP will attempt to send the httponly flag when setting the session cookie. } //function ownSetCookieParams($cooArr) { public function ownSetCookie() { //$cooArr= [ string $name [, string $value = "" [, int $expire = 0 //[, string $path = "" [, string $domain = "" [, //bool $secure = false [, bool $httponly = false ]]]]]] ] $params = session_get_cookie_params(); echo "<br><br> 21 Sessiong, cookie params after session start ="; print_r($params); $this->sessid = session_id(); setcookie( $this->sessName, $this->sessid, $this->timelimit, $this->path, $this->domain, $this->ifhttps ); $params = session_get_cookie_params(); echo "<br><br> 21 Sessiong, cookie params after setcookie ="; print_r($params); } public function genRedirToken() { $this->redirToken = 'random string , most probably jwt token'; $_SESSION['rt'] = $this->redirToken; return $this->redirToken; } public function ownSetMainSessionParams($sesArr=[]) { $now = time(); // seconds $timelimit = !empty($sesArr['timelimit']) ? $sesArr['timelimit'] : $this->timelimit; $_SESSION['sessStart'] = $now; $_SESSION['sessEnd'] = $now + $timelimit; $_SESSION['userId'] = !empty($sesArr['userId']) ? $sesArr['userId'] : USER_ANONYMOUS_ID; $_SESSION['username'] = !empty($sesArr['username']) ? $sesArr['username'] : USER_ANONYMOUS_NAME; $_SESSION['roles'] = !empty($sesArr['roles']) ? $sesArr['roles'] : [ USER_ANONYMOUS_ROLES ]; //$this->genRedirToken(); //$_SESSION['rt'] = $this->redirToken; $this->redirToken=generated str... $_SESSION['sessLooseIp'] = long2ip(ip2long($_SERVER['REMOTE_ADDR']) & ip2long("255.255.0.0")); $_SESSION['sessLooseAgent'] = substr($_SERVER['HTTP_USER_AGENT'],0,25); } // https://wblinks.com/notes/secure-session-management-tips/ public function checkSession ($vdArr=[]) { $errSesArr = []; //- FINISH TO IMPLEMENT - check url parameters - must be part of custom request // but also applicable here .... . //- FINISH TO IMPLEMENT //not always applicable, applicable only in case if not redirect //but i redirect only to login, logout, chars exercise, error, thus must be within these //additionally during redirection there are only lang/redirToken paramemters, not more - double check parameters //if ( isset($vdArr['path'] ) && ($_SESSION['prevPage'] != $vdArr['path']) ){ // $errSesArr [] = "Path is different"; // means different browser //} //double check, because buffering may change path and PHP_SELF value ! //$_SERVER['PHP_SELF'] in a script at the address http://example.com/foo/bar.php would be /foo/bar.php. //The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP if(!empty($vdArr['path'])) { if( 'public/index.php/'.$vdArr['path'] != $_SERVER['PHP_SELF'] ) { $errSesArr [] = "Path is different"; // means different browser } } if ($_SESSION['sessLooseIp'] != long2ip(ip2long($_SERVER['REMOTE_ADDR']) & ip2long("255.255.0.0")) ) { $errSesArr [] = "Loose Ip different"; // means different country } if ( $_SESSION['sessLooseAgent'] != substr($_SERVER['HTTP_USER_AGENT'],0,25) ){ $errSesArr [] = "Useragent different"; // means different browser } if ( (!empty($vdArr['rt']) && !empty($_SESSION['rt']) && $_SESSION['rt'] != $vdArr['rt']) || ( $_SESSION['sessCount'] == 0 && empty($vdArr['rt']) )// the first request, rt is not set. ){ $errSesArr [] = "Session token is different"; // means different browser } //server IP if( !in_array( $_SERVER['SERVER_ADDR'], $this->serverAddrArr ) ){ $errSesArr[] = "Server address ".$_SERVER['SERVER_ADDR']." is not amont safe listed. Contact the administrator"; // means different browse } //if( $_SERVER['SERVER_NAME'] != $this->serverName ) { if( !in_array( $_SERVER['SERVER_NAME'], $this->serverName ) ){ $errSesArr[] = "Server name ".$_SERVER['SERVER_NAME']." is not the one considered to be safe."; } if ( $_SESSION['sessionId'] !== session_id()) { $errSesArr[] = "Session ID ". session_id() ." is invalud."; } //report error, //record IP and other paramters commented-out below if( !empty($_SESSION['prevPath']) && ($_SESSION['prevPath']==$vdArr['path'] ) ) { //correct redirections are to ErrArr from any page, also echo "<br><br> Sessiong, redirection. HERE must be redirection table check"; } else { echo "<br><br> Sessiong, no redirection"; } // redirection - special function checking possible redirection from given MAP //echo "<br><br>Sesssion.php 61 vdArr=<br>"; var_dump($vdArr); //echo "<br><br>Sesssion.php 62 Session=<br>";var_dump($_SESSION); if( !empty($vdArr['rt']) && ($vdArr['rt']===$_SESSION['rt']) ) { //proceed, everything is alright with redirection echo "<br> 261 Session.php everyhting is alright with redirection"; } //generate an error, record ip. else { //own_session_destory() echo '<br><br> 261 Session.php, you was redirected from wrong page'; } if( !empty($errSesArr) ) { //$this->own_logout($errSesArr); echo "<br><br> FINISH implement, session.php 272 !empty(errSesArr)"; print_r($errSesArr); $errcode = md5( uniqid(microtime(), true) ) . $this->genRandomStr(5) ; $msgErr = 'It was detected suspicious activities. Please re-login to continue or contact the administrator with err number :'.$errcode ; //delete session, create a new session $this->ownSetMainSessionParams( [ 'msgErr'=>$msgErr ] ); //redirect } // includes ownSessionDestroy(); , ownSessionStart(); userMsg, own_logout(), htt->login } //function checkSession () { public function ownSessionDestroy() { //https://wblinks.com/notes/secure-session-management-tips/ setcookie( $this->sessName, $this->sessionId, 1); //The correct way to clear a cookie is to just pass in 1 as the expiry time. session_unset();// Same as $_SESSION = array(); Destroy session on disk session_destroy(); } public function ownDealExpiredSession() { $this->ownSessionDestroy(); $this->ownSessionStart(); //generates a new redirToken $msgErr = $this->msgsessEnd; //$this->ownSetMainSessionParams( [ 'msgErr'=>$msgErr ] ); echo "<br> 345 Session.php, session expired redirecting to login"; } // public function ownDealExpiredSess() { public function ownSessionStart() { //ownCheckCookiesEnabled(); $this->ownSetCookieParams(); session_start(); $_SESSION['sessCount'] = 0; //$_SESSION['valid_id'] = session_id(); $this->sessionId = session_id(); $_SESSION['sessionId'] = $this->sessionId; // $this->ownSetCookie(); $this->ownSetMainSessionParams(); // does not generete redirToken echo "<br><br> 427 sessiong.php, After ownSessionStart _SESSION="; print_r($_SESSION); } //function ownSessionStart() { public function ownContinueSession() { //if( ( !empty($_SESSION['start'])) && ( $now <= ($_SESSION['start'] + $timelimit) ) ) { $now = time(); $_SESSION['sessStart'] = $now; $_SESSION['sessEnd'] = $now + $this->timelimit; $_SESSION['sessCount']++; //counts how many times session was activated } public function ownRegenerateSessionId() { $status = session_status(); echo "<br><br> 448 Sessiong.php, ownRegenerateSessionId session_status=". $status; if( $status == PHP_SESSION_ACTIVE || $status ==2 ) { $oldSession = $_SESSION; echo "session.php session is not expired, oldSession="; print_r($oldSession); echo "session.php session is not expired, oldSessionId=".$this->sessionId; session_regenerate_id(true); //this destroys the old session, but others says it is wrong $this->sessionId = session_id(); $_SESSION = $oldSession; //$_SESSION['validId'] = $this->sessionId; //regenerates redirToken echo "session.php session is not expired, newSession="; print_r($_SESSION); echo "session.php session is not expired, newSessionId=" .$this->sessionId; } } public function ownDealSession() { // $_SESSION['rt'] = $token; // Redir token $now = time(); //token to be retrieved from all redirections, to be compared if correct - part of this file echo "<br><br> 462 ownDealSession, _SESSION="; print_r($_SESSION); echo "<br>ownDealSession now=" . $now; if(!isset($_SESSION) || empty($_SESSION) ) { echo "<br><br> 465 Sessiong.php ownSessionStart"; $this->ownSessionStart(); echo "<br><br> case not set-empty, _SESSION="; print_r($_SESSION); //if (!empty($_COOKIE[session_name()])) { setcookie(session_name(), '', time()-86400, 'https://www.typejoy.biz/'); } } // *** SESSION ALREADY EXISTS, but exceed the time limit else if ( !empty($_SESSION['sessStart']) && !empty($_SESSION['sessEnd']) && ( $now > intval($_SESSION['sessEnd'])) ) { echo "<br>ownDealSession ase (!empty sessStart) and (now>sessEnd),now=" . $now; $this->ownDealExpiredSession(); echo "<br><br> case (!empty sessStart) and (time>sessEnd), _SESSION="; print_r($_SESSION); } else if( !empty($_SESSION['sessStart']) && !empty($_SESSION['sessEnd']) && ( $now <= intval($_SESSION['sessEnd']) ) ) { echo "<br><br>474 Sessiong.php (!empty sessStart) and (now<=sessEnd) "; echo "<br>ownDealSession now=" . $now; $this->ownContinueSession(); //$bsafe = $this->checkSession($vdArr); //redirect here // $this->ownRegenerateSessionId(); $this->genRedirToken(); echo "<br><br> case (!empty sessStart) and (now<=sessEnd), _SESSION="; print_r($_SESSION); }// elseif( ( !empty($_SESSION['start'])) && ( $now <= ($_SESSION['start'] + $timelimit) ) ) { else { echo "<br><br>481, Sessiong not clear case"; echo "<br>ownDealSession sessStart=" . $_SESSION['sessStart']; echo "<br>ownDealSession now=" . $now; echo "<br>ownDealSession sessEnd=" . $_SESSION['sessEnd']; } $params = session_get_cookie_params(); echo "<br><br> 508 Sessiong, cookie params in the end of ownDealSession ="; print_r($params); } //public function dealSession() { public function setIfEmpty($givArr){ $retFull=[]; foreach($givArr as $k=>$v) { if(empty($_SESSION[$k])) { $_SESSION[$k]=$v; } else { $retFull[] = $k; } } return $retFull; //returns array with keys which have values in _SESSION } public function set($givArr) { foreach($givArr as $k=>$v) { $_SESSION[$k]=$v; } } //if( isset($_SESSION['curPath']) ) { $_SESSION['prevPath'] = $_SESSION['curPath']; } //if( isset($_SESSION['curAction']) ) { $_SESSION['prevAction'] = $_SESSION['curAction']; } //$this->sess->setCond( [ // [ 'vars'=> [ 'curPath'=> $vdArr['path'] ], 'cond'=> isset($_SESSION['curPath']) ], // [ 'vars'=> [ 'curAction'=>$vdArr['action']], 'cond'=> isset($_SESSION['curAction']) ], // ] ); public function setCond($givArr) { foreach($givArr as $cond) { if($cond['cond']) { foreach($cond['vars'] as $k=>$v) { $_SESSION[$k]=$v; }}}} } //

2)在我创建新会话后的函数ownDealSession中

Notice: Undefined variable: _SESSION in ...\Sessiong.php on line 477

3)在我创建新会话

之后的函数ownDealSession中
sessiong.php, After ownSessionStart _SESSION=Array ( [sessCount] => 0 [sessionId] => l89mnggsjmpgtp5n2dqsuo2rm6 [sessStart] => 1494406265 [sessEnd] => 1494409865 [userId] => 25 [username] => anon [roles] => Array ( [0] => IS_AUTHENTICATED_ANONYMOUSLY ) [sessLooseIp] => 0.0.0.0 [sessLooseAgent] => Mozilla/5.0 (Windows NT 1 [rt] => 'random string , most probably jwt token' [path] => democurpath [action] => democur30 ...

0 个答案:

没有答案
相关问题