Exemple #1
1
 static function start()
 {
     include_once __DIR__ . '/sessionDrivers/' . Settings::$sessionDriver . '.php';
     //self::$driver = new Settings::$sessionDriver();
     //session_set_save_handler(array(self::$driver, 'open'),array(self::$driver, 'close'),array(self::$driver, 'read'),
     //            array(self::$driver, 'write'),array(self::$driver, 'destroy'),array(self::$driver, 'gc'));
     register_shutdown_function('session_write_close');
     if (in_array(Settings::$session_hash, hash_algos())) {
         ini_set('session.hash_function', Settings::$session_hash);
     }
     ini_set('session.hash_bits_per_character', Settings::$hash_bits_per_character);
     $cookieParams = session_get_cookie_params();
     session_set_cookie_params(Settings::$sessionLifetime, $cookieParams["path"], $cookieParams["domain"], Settings::$secure, Settings::$httpOnly);
     session_name(Settings::$NAME);
     //буферизуем заголовок
     ob_start();
     //включаем CORS, если указано в настройках /*
     if (isset(Settings::$CORS) && Settings::$CORS && !empty($_SERVER['HTTP_ORIGIN'])) {
         header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
         header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
         header('Access-Control-Max-Age: 1000');
         header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
     }
     //включаем сессию
     session_start();
     ob_end_flush();
     //посылаем заголовок
 }
Exemple #2
1
 /**
  * Initialize session
  */
 public static function init()
 {
     // Force cookie path (but do not change lifetime)
     $cookie = session_get_cookie_params();
     // Default cookie expiration and path.
     $cookiedir = '';
     if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
         $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
     }
     $ssl = false;
     if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
         $ssl = true;
     }
     session_set_cookie_params($cookie['lifetime'], $cookiedir, $cookie['domain'], $ssl);
     // Use cookies to store session.
     ini_set('session.use_cookies', 1);
     // Force cookies for session  (phpsessionID forbidden in URL)
     ini_set('session.use_only_cookies', 1);
     if (!session_id()) {
         // Prevent php to use sessionID in URL if cookies are disabled.
         ini_set('session.use_trans_sid', false);
         if (!empty(self::$sessionName)) {
             session_name(self::$sessionName);
         }
         session_start();
     }
 }
function _set_session_start_()
{
    global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS;
    $var_session = true;
    if (isset($HTTP_GET_VARS[_set_session_name_()])) {
        if (preg_match("/^[a-zA-Z0-9]+\$/", $HTTP_GET_VARS[_set_session_name_()]) == false) {
            unset($HTTP_GET_VARS[_set_session_name_()]);
            $var_session = false;
        }
    } elseif (isset($HTTP_POST_VARS[_set_session_name_()])) {
        if (preg_match("/^[a-zA-Z0-9]+\$/", $HTTP_POST_VARS[_set_session_name_()]) == false) {
            unset($HTTP_POST_VARS[_set_session_name_()]);
            $var_session = false;
        }
    } elseif (isset($HTTP_COOKIE_VARS[_set_session_name_()])) {
        if (preg_match("/^[a-zA-Z0-9]+\$/", $HTTP_COOKIE_VARS[_set_session_name_()]) == false) {
            $var_session_data = session_get_cookie_params();
            setcookie(_set_session_name_(), "", time() - 42000, $var_session_data["path"], $var_session_data["domain"]);
            $var_session = false;
        }
    }
    if ($var_session == false) {
        _set_location_(def_application_home);
    }
    return session_start();
}
Exemple #4
0
 function iniciarSesion($session_name, $secure)
 {
     // Make sure the session cookie is not accessable via javascript.
     $httpunico = true;
     // Hash algorithm to use for the sessionid. (use hash_algos() to get a list of available hashes.)
     $sesion_hash = 'sha512';
     // Check if hash is available
     if (in_array($sesion_hash, hash_algos())) {
         // Set the has function.
         ini_set('session.hash_function', $sesion_hash);
     }
     // How many bits per character of the hash.
     // The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ",").
     ini_set('session.hash_bits_per_character', 5);
     // Force the session to only use cookies, not URL variables.
     ini_set('session.use_only_cookies', 1);
     // Get session cookie parameters
     $cookieParams = session_get_cookie_params();
     // Set the parameters
     session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httpunico);
     // Change the session name
     session_name($session_name);
     // Now we cat start the session
     session_start();
     // This line regenerates the session and delete the old one.
     // It also generates a new encryption key in the database.
 }
 /**
  * Available options:
  *
  *  * session_name:            The cookie name (symfony by default)
  *  * session_id:              The session id (null by default)
  *  * auto_start:              Whether to start the session (true by default)
  *  * session_cookie_lifetime: Cookie lifetime
  *  * session_cookie_path:     Cookie path
  *  * session_cookie_domain:   Cookie domain
  *  * session_cookie_secure:   Cookie secure
  *  * session_cookie_httponly: Cookie http only (only for PHP >= 5.2)
  *
  * The default values for all 'session_cookie_*' options are those returned by the session_get_cookie_params() function
  *
  * @param array $options  An associative array of options
  *
  * @see sfStorage
  */
 public function initialize($options = null)
 {
     $cookieDefaults = session_get_cookie_params();
     $options = array_merge(array('session_name' => 'symfony', 'session_id' => null, 'auto_start' => true, 'session_cookie_lifetime' => $cookieDefaults['lifetime'], 'session_cookie_path' => $cookieDefaults['path'], 'session_cookie_domain' => $cookieDefaults['domain'], 'session_cookie_secure' => $cookieDefaults['secure'], 'session_cookie_httponly' => isset($cookieDefaults['httponly']) ? $cookieDefaults['httponly'] : false, 'session_cache_limiter' => 'none'), $options);
     // initialize parent
     parent::initialize($options);
     // set session name
     $sessionName = $this->options['session_name'];
     session_name($sessionName);
     if (!(bool) ini_get('session.use_cookies') && ($sessionId = $this->options['session_id'])) {
         session_id($sessionId);
     }
     $lifetime = $this->options['session_cookie_lifetime'];
     $path = $this->options['session_cookie_path'];
     $domain = $this->options['session_cookie_domain'];
     $secure = $this->options['session_cookie_secure'];
     $httpOnly = $this->options['session_cookie_httponly'];
     session_set_cookie_params($lifetime, $path, $domain, $secure, $httpOnly);
     if (!is_null($this->options['session_cache_limiter'])) {
         session_cache_limiter($this->options['session_cache_limiter']);
     }
     if ($this->options['auto_start'] && !self::$sessionStarted) {
         session_start();
         self::$sessionStarted = true;
     }
 }
 public function init($options = null)
 {
     $cookie_defaults = session_get_cookie_params();
     if (!isset($options['session_cookie_path']) && class_exists("waSystem")) {
         $options['session_cookie_path'] = waSystem::getInstance()->getRootUrl();
     }
     $options = array_merge(array('session_id' => null, 'auto_start' => true, 'session_cookie_lifetime' => $cookie_defaults['lifetime'], 'session_cookie_path' => $cookie_defaults['path'], 'session_cookie_domain' => $cookie_defaults['domain'], 'session_cookie_secure' => $cookie_defaults['secure'], 'session_cookie_httponly' => true, 'session_cache_limiter' => 'none'), $options);
     // initialize parent
     parent::init($options);
     if (isset($this->options['session_name'])) {
         session_name($this->options['session_name']);
     }
     if (!(bool) ini_get('session.use_cookies') && ($session_id = $this->options['session_id'])) {
         session_id($session_id);
     }
     $lifetime = $this->options['session_cookie_lifetime'];
     $path = $this->options['session_cookie_path'];
     $domain = $this->options['session_cookie_domain'];
     $secure = $this->options['session_cookie_secure'];
     $http_only = $this->options['session_cookie_httponly'];
     session_set_cookie_params($lifetime, $path, $domain, $secure, $http_only);
     if (null !== $this->options['session_cache_limiter']) {
         session_cache_limiter($this->options['session_cache_limiter']);
     }
     if ($this->options['auto_start']) {
         if (isset($_COOKIE[session_name()])) {
             $this->open();
         }
     }
 }
Exemple #7
0
function ensure_session()
{
    if (session_id() !== "") {
        return true;
    }
    if (!($sn = make_session_name(opt("sessionName")))) {
        return false;
    }
    // maybe upgrade from an old session name to this one
    if (!isset($_COOKIE[$sn]) && ($upgrade_sn = opt("sessionUpgrade")) && ($upgrade_sn = make_session_name($upgrade_sn)) && isset($_COOKIE[$upgrade_sn])) {
        session_id($_COOKIE[$upgrade_sn]);
        setcookie($upgrade_sn, "", time() - 3600, "/", opt("sessionUpgradeDomain", opt("sessionDomain", "")), opt("sessionSecure", false));
    }
    $secure = opt("sessionSecure");
    $domain = opt("sessionDomain");
    if ($secure !== null || $domain !== null) {
        $params = session_get_cookie_params();
        if ($secure !== null) {
            $params["secure"] = !!$secure;
        }
        if ($domain !== null) {
            $params["domain"] = $domain;
        }
        session_set_cookie_params($params["lifetime"], $params["path"], $params["domain"], $params["secure"]);
    }
    session_name($sn);
    session_cache_limiter("");
    if (isset($_COOKIE[$sn]) && !preg_match(';\\A[-a-zA-Z0-9,]{1,128}\\z;', $_COOKIE[$sn])) {
        error_log("unexpected session ID <" . $_COOKIE[$sn] . ">");
        unset($_COOKIE[$sn]);
    }
    session_start();
    return true;
}
Exemple #8
0
 /**
  *
  * Constructor
  *
  * @param SegmentFactory $segment_factory A session segment factory.
  *
  * @param                CsrfTokenFactory A CSRF token factory.
  *
  * @param array          $cookies         An arry of cookies from the client, typically a
  *                                        copy of $_COOKIE.
  *
  */
 public function __construct(SegmentFactory $segment_factory, CsrfTokenFactory $csrf_token_factory, array $cookies = array())
 {
     $this->segment_factory = $segment_factory;
     $this->csrf_token_factory = $csrf_token_factory;
     $this->cookies = $cookies;
     $this->cookie_params = session_get_cookie_params();
 }
Exemple #9
0
 /**
  *
  */
 public function destroyCookie()
 {
     if (ini_get("session.use_cookies")) {
         $params = session_get_cookie_params();
         setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
     }
 }
Exemple #10
0
 /**
  * Logs out a user and resets the complete session
  * @author  Clemens John <*****@*****.**>
  * @return boolean true if the logout was successfull
  */
 public function user_logout()
 {
     if (!isset($_SESSION['user_id'])) {
         $messages[] = array("Sie können sich nicht ausloggen, wenn Sie nicht eingeloggt sind", 2);
         Message::setMessage($messages);
         return false;
     } else {
         //destroy current session
         //to correctly destroy a session look at http://php.net/manual/de/function.session-destroy.php
         $stmt = DB::getInstance()->prepare("UPDATE users SET session_id = ? WHERE id = ?");
         $stmt->execute(array('', $_SESSION['user_id']));
         //delete all Remember-Mes from the database (TODO: this could be improved by storing
         //the current session id along with the remember me and then delete only the remember me
         //coresponding to the current session.
         $user_remember_me_list = new UserRememberMeList($_SESSION['user_id']);
         $user_remember_me_list->delete();
         unset($_SESSION);
         unset($_COOKIE);
         setcookie("remember_me", "", time() - 60 * 60 * 24 * 14);
         setcookie(session_name(), '', time() - 3600, '/');
         if (ini_get("session.use_cookies")) {
             $params = session_get_cookie_params();
             setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
         }
         session_destroy();
         session_start();
         $messages[] = array("Sie wurden ausgeloggt und ihre Benutzersession wurde gelöscht!", 1);
         Message::setMessage($messages);
         return true;
     }
 }
 public function indexAction()
 {
     $this->_helper->layout()->disableLayout();
     if (isset($_COOKIE['icingaweb2-session'])) {
         $last = (int) $_COOKIE['icingaweb2-session'];
     } else {
         $last = 0;
     }
     $now = time();
     if ($last + 600 < $now) {
         Session::getSession()->write();
         $params = session_get_cookie_params();
         setcookie('icingaweb2-session', $now, null, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
         $_COOKIE['icingaweb2-session'] = $now;
     }
     $announcementCookie = new AnnouncementCookie();
     $announcementRepo = new AnnouncementIniRepository();
     if ($announcementCookie->getEtag() !== $announcementRepo->getEtag()) {
         $announcementCookie->setEtag($announcementRepo->getEtag())->setNextActive($announcementRepo->findNextActive());
         $this->getResponse()->setCookie($announcementCookie);
         $this->getResponse()->setHeader('X-Icinga-Announcements', 'refresh', true);
     } else {
         $nextActive = $announcementCookie->getNextActive();
         if ($nextActive && $nextActive <= $now) {
             $announcementCookie->setNextActive($announcementRepo->findNextActive());
             $this->getResponse()->setCookie($announcementCookie);
             $this->getResponse()->setHeader('X-Icinga-Announcements', 'refresh', true);
         }
     }
     $this->getResponse()->setHeader('X-Icinga-Container', 'ignore', true);
 }
Exemple #12
0
 /**
  * @param array $config
  */
 public function __construct(array $config = [])
 {
     // make sure we've got all config elements for this driver
     $config['native'] = array_merge($this->defaults, isset($config['native']) ? $config['native'] : array());
     // call the parent to process the global config
     parent::__construct($config);
     // get default the cookie params
     $params = session_get_cookie_params();
     // update them with any config passed
     if (isset($config['cookie_domain'])) {
         $params['domain'] = $config['cookie_domain'];
     }
     if (isset($config['cookie_path'])) {
         $params['path'] = $config['cookie_path'];
     }
     if (isset($config['cookie_secure']) and $config['cookie_secure']) {
         $params['secure'] = true;
     }
     if (isset($config['cookie_http_only']) and $config['cookie_http_only']) {
         $params['httponly'] = true;
     }
     if (isset($config['expire_on_close']) and $config['expire_on_close']) {
         $params['lifetime'] = 0;
     }
     session_set_cookie_params($this->expiration, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
     // store the defined name
     if (isset($config['native']['cookie_name'])) {
         $this->name = $config['native']['cookie_name'];
     }
 }
Exemple #13
0
 protected function setCookie()
 {
     $data = json_encode($this->_data);
     $sig = $this->_sig($data . $this->_getCookieDomain(), $this->getOption('secret'));
     $params = session_get_cookie_params();
     Pix_HttpResponse::setcookie($this->_getCookieKey(), $sig . '|' . $data, $this->_getTimeout() ? time() + $this->_getTimeout() : null, $this->_getCookiePath(), $this->_getCookieDomain());
 }
 /**
  * Index Page for this controller.
  */
 public function index()
 {
     // Initialize the session.
     if ($this->is_session_started() === FALSE) {
         session_start();
     }
     // Unset all of the session variables.
     $_SESSION = array();
     // If it's desired to kill the session, also delete the session cookie.
     // Note: This will destroy the session, and not just the session data!
     if (ini_get("session.use_cookies")) {
         $params = session_get_cookie_params();
         setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
     }
     // Finally, destroy the session.
     if ($this->is_session_started() === TRUE) {
         session_unset();
         session_destroy();
     }
     // $session_data = $this->session->all_userdata();
     //
     // foreach($session_data as $key => $value) {
     //   $this->session->unset_userdata($key);
     // }
     //
     // $this->session->sess_destroy();
     redirect("/", 302);
 }
Exemple #15
0
function sec_session_start()
{
    $session_name = 'examen_session_id';
    // Asignamos un nombre de sesión.
    $secure = false;
    // Mejor en config.php Lo ideal sería true para trabajar con https.
    $httponly = true;
    // Obliga a la sesión a utilizar solo cookies.
    // Habilitar este ajuste previene de ataques que implican pasar el id de sesión en la URL.
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        $action = "error";
        $error = "No puedo iniciar una sesion segura (ini_set)";
    }
    // Obtener los parámetros de la cookie de sesión
    $cookies = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
    //Marca la cookie como accesible sólo a través del protocolo HTTP.
    // Esto siginifica que la cookie no será accesible por lenguajes de script,
    // tales como JavaScript.
    // Este ajuste puede ayudar de manera efectiva a reducir robos de
    // indentidad a través de ataques.
    // Incia la sesión PHP
    session_name($session_name);
    session_start();
    // Actualiza el id de sesión actual con uno generado más reciente.
    // Ayuda a evitar ataques de fijación de sesión.
    session_regenerate_id(true);
}
Exemple #16
0
 public static function start()
 {
     //if(self::$started)
     //	return true;
     // DEBUG: Ver un nombre con alguna llave random al momentode instalar.
     $session_name = 'Bludit-KEY';
     // If TRUE cookie will only be sent over secure connections.
     $secure = false;
     // If set to TRUE then PHP will attempt to send the httponly flag when setting the session cookie.
     $httponly = true;
     // This specifies the lifetime of the cookie in seconds which is sent to the browser.
     // The value 0 means until the browser is closed.
     $cookieLifetime = 0;
     // Gets current cookies params.
     $cookieParams = session_get_cookie_params();
     session_set_cookie_params($cookieLifetime, $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
     // Sets the session name to the one set above.
     session_name($session_name);
     // Start session.
     self::$started = session_start();
     // Regenerated the session, delete the old one. There are problems with AJAX.
     //session_regenerate_id(true);
     if (!self::$started) {
         Log::set(__METHOD__ . LOG_SEP . 'Error occurred when trying to start the session.');
     }
 }
Exemple #17
0
/**
 * Destruction coomplète de la session et des cookies
 * @param boolean $rediRectToIndex Est ce que je dois rediriger vers l'index
 * @param boolean $stopExec Est ce que je fais un exit après l'exécution de la 
 * fonction
 */
function stopSession($rediRectToIndex = TRUE, $stopExec = FALSE, $extra = 'index.php?redirect=0')
{
    global $config;
    if (isset($_SESSION[$config['sessionName']])) {
        session_unset();
        session_destroy();
        // Unset all of the session variables.
        $_SESSION = array();
    }
    // If it's desired to kill the session, also delete the session cookie.
    // Note: This will destroy the session, and not just the session data!
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        foreach ($_COOKIE as $key => $value) {
            setcookie($key, '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
        }
    }
    if ($rediRectToIndex == TRUE) {
        /* 
         * Redirection vers une page différente du même dossier 
         * le @ permet de pouvoir appeler la fonction ans générer d'erreur
         */
        $host = @$_SERVER['HTTP_HOST'];
        $uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
        $curUri = rtrim(basename($_SERVER['PHP_SELF']), '/\\');
        if (!isset($_GET['redirect'])) {
            header("Location: http://{$host}{$uri}/{$extra}");
        }
    } else {
        echo 'true';
    }
    if ($stopExec) {
        exit;
    }
}
Exemple #18
0
function destroy_session()
{
    $session_info = session_get_cookie_params();
    $_SESSION = [];
    setcookie(session_name(), '', 0, $session_info['path'], $session_info['domain'], $session_info['secure'], $session_info['httponly']);
    session_destroy();
}
Exemple #19
0
 /**
  * Destroy session.
  */
 public static function destroySession()
 {
     $_SESSION = array();
     $params = session_get_cookie_params();
     setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
     session_destroy();
 }
Exemple #20
0
 /**
  * @param Request $request
  * @param int     $type
  * @param bool    $catch
  *
  * @return Response
  * @throws \Exception
  */
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
 {
     if ($type === HttpKernelInterface::SUB_REQUEST) {
         return $this->app->handle($request, $type, $catch);
     }
     $parameters = $this->config->get('cookie_parameters');
     if (!isset($parameters[$this->config->get('current_locale')])) {
         throw new \Exception(sprintf('Domain %s not available', $this->config->get('current_locale')));
     }
     $cookieParams = $parameters[$this->config->get('current_locale')];
     $this->config->set('current_cookie_domain', $cookieParams['domain']);
     if (HttpKernelInterface::MASTER_REQUEST !== $type) {
         return $this->app->handle($request, $type, $catch);
     }
     $session = new Session();
     $request->setSession($session);
     $cookies = $request->cookies;
     if ($cookies->has($session->getName())) {
         $session->setId($cookies->get($session->getName()));
     } else {
         //starts the session if no session exists
         $session->start();
         $session->migrate(false);
     }
     $session->start();
     $response = $this->app->handle($request, $type, $catch);
     if ($session && $session->isStarted()) {
         $session->save();
         $params = array_merge(session_get_cookie_params(), $cookieParams);
         $cookie = new Cookie($session->getName(), $session->getId(), 0 === $params['lifetime'] ? 0 : $request->server->get('REQUEST_TIME') + $params['lifetime'], $params['path'], $params['domain'], $params['secure'], $params['httponly']);
         $response->headers->setCookie($cookie);
     }
     return $response;
 }
function pageController()
{
    require_once '../php/parks_login.php';
    require_once '../php/db_connect.php';
    $page = isset($_GET['page']) && $_GET['page'] > -1 ? $_GET['page'] : 0;
    $limit = isset($_GET['limit']) ? $_GET['limit'] : 5;
    $offset = isset($_GET['offset']) ? $_GET['offset'] : $page * $limit;
    $newoffset = $limit === '10' ? '5' : '10';
    $stmt = $dbc->prepare("SELECT * FROM national_parks LIMIT :limit OFFSET :offset");
    $stmt->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', (int) $offset, PDO::PARAM_INT);
    $stmt->execute();
    if (isset($_GET['admin']) && $_GET['admin'] === 'true') {
        $_SESSION['admin'] = true;
    }
    if (isset($_GET['logout']) && $_GET['logout'] === 'true') {
        // Unset all of the session variables.
        $_SESSION = array();
        // If it's desired to kill the session, also delete the session cookie.
        // Note: This will destroy the session, and not just the session data!
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
        }
        // Finally, destroy the session.
        session_destroy();
    }
    $results = $stmt->fetchall(PDO::FETCH_ASSOC);
    return array('page' => $page, 'limit' => $limit, 'offset' => $offset, 'newoffset' => $newoffset, 'results' => $results);
}
Exemple #22
0
 public function regenerate()
 {
     global $user;
     if (!$this->sessionIsEmpty()) {
         $currentData = $_SESSION;
     }
     if ($this->started) {
         $this->started = FALSE;
         session_destroy();
         // Remove potential remaining cookie.
         setcookie($this->sessionName, FALSE);
     }
     $this->generateSessionIdentifier();
     if (isset($currentData) && !empty($currentData)) {
         $_SESSION = $currentData;
         $this->start();
         if ($user->uid) {
             $_SESSION['uid'] = $user->uid;
         }
     } else {
         if ($user->uid) {
             $this->start();
             $_SESSION['uid'] = $user->uid;
         }
     }
     if ($this->started) {
         // Some PHP versions won't reset correctly the cookie.
         $params = session_get_cookie_params();
         $expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;
         setcookie($this->sessionName, $this->sessionIdentifier, $expire, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
     }
     $this->refreshAfterSessionChange();
 }
function sec_session_start()
{
    $session_name = 'sec_session_id';
    // Set a custom session name
    $secure = false;
    // Set to true if using https.
    $httponly = true;
    // This stops javascript being able to access the session id.
    ini_set('session.use_only_cookies', 1);
    // Forces sessions to only use cookies.
    $cookieParams = session_get_cookie_params();
    // Gets current cookies params.
    session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
    session_name($session_name);
    // Sets the session name to the one set above.
    session_start();
    // Start the php session
    session_regenerate_id(false);
    // regenerated the session, delete the old one.
    $inactive = 600;
    // check to see if $_SESSION['timeout'] is set
    if (isset($_SESSION['timeout'])) {
        $session_life = time() - $_SESSION['timeout'];
        if ($session_life > $inactive) {
            echo "<script language=javascript>\n\t\talert('Sesi Telah Habis');</script>";
            echo '<script type=text/javascript>
		window.location = "logout.php";
		</script>';
        }
    }
    $_SESSION['timeout'] = time();
}
 /**
  * Returns current session cookie configuration
  * @return array
  */
 public function getCookieOptions()
 {
     // Get default cookie options
     $options = session_get_cookie_params();
     // Cookie name
     $options['name'] = session_name();
     if (!empty($this->_options['cookie']['name'])) {
         $options['name'] = (string) $this->_options['cookie']['name'];
     }
     // Cookie lifetime
     if (!empty($this->_options['cookie']['lifetime'])) {
         $options['lifetime'] = (int) $this->_options['cookie']['lifetime'];
     }
     // Path
     if (!empty($this->_options['cookie']['path'])) {
         $options['path'] = (string) $this->_options['cookie']['path'];
     }
     // Domain
     if (!empty($this->_options['cookie']['domain'])) {
         $options['domain'] = (string) $this->_options['cookie']['domain'];
     }
     // Secure
     if (!empty($this->_options['cookie']['secure'])) {
         $options['secure'] = (bool) $this->_options['cookie']['secure'];
     }
     // Http only
     if (!empty($this->_options['cookie']['httponly'])) {
         $options['httponly'] = (bool) $this->_options['cookie']['httponly'];
     }
     return $options;
 }
 /**
  * Initializes this Storage instance.
  *
  * @param sfContext A sfContext instance
  * @param array   An associative array of initialization parameters
  *
  * @return boolean true, if initialization completes successfully, otherwise false
  *
  * @throws <b>sfInitializationException</b> If an error occurs while initializing this Storage
  */
 public function initialize($context, $parameters = null)
 {
     // initialize parent
     parent::initialize($context, $parameters);
     // set session name
     $sessionName = $this->getParameterHolder()->get('session_name', 'symfony');
     session_name($sessionName);
     $use_cookies = (bool) ini_get('session.use_cookies');
     if (!$use_cookies) {
         $sessionId = $context->getRequest()->getParameter($sessionName, '');
         if ($sessionId != '') {
             session_id($sessionId);
         }
     }
     $cookieDefaults = session_get_cookie_params();
     $lifetime = $this->getParameter('session_cookie_lifetime', sfConfig::get('sf_timeout'));
     $path = $this->getParameter('session_cookie_path', $cookieDefaults['path']);
     $domain = $this->getParameter('session_cookie_domain', $cookieDefaults['domain']);
     $secure = $this->getParameter('session_cookie_secure', $cookieDefaults['secure']);
     $httpOnly = $this->getParameter('session_cookie_httponly', isset($cookieDefaults['httponly']) ? $cookieDefaults['httponly'] : false);
     if (version_compare(phpversion(), '5.2', '>=')) {
         session_set_cookie_params($lifetime, $path, $domain, $secure, $httpOnly);
     } else {
         session_set_cookie_params($lifetime, $path, $domain, $secure);
     }
     if ($this->getParameter('auto_start', true)) {
         // start our session
         session_start();
     }
 }
Exemple #26
0
 /**
  * {@inheritDoc}
  */
 public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $type) {
         return $this->app->handle($request, $type, $catch);
     }
     $session = new SymfonySession();
     $request->setSession($session);
     if ($this->start) {
         $cookies = $request->cookies;
         if ($cookies->has($session->getName())) {
             $session->setId($cookies->get($session->getName()));
         } else {
             //starts the session if no session exists
             $session->start();
             $session->migrate(false);
         }
         $session->start();
     }
     $response = $this->app->handle($request, $type, $catch);
     if ($session && $session->isStarted()) {
         $session->save();
         $params = array_merge(session_get_cookie_params(), $this->cookieParams);
         if (array_key_exists('domain', $this->cookieParams)) {
             $response->headers->clearCookie($session->getName());
         }
         $cookie = new Cookie($session->getName(), $session->getId(), 0 === $params['lifetime'] ? 0 : $request->server->get('REQUEST_TIME') + $params['lifetime'], $params['path'], $params['domain'], $params['secure'], $params['httponly']);
         $response->headers->setCookie($cookie);
     }
     return $response;
 }
Exemple #27
0
  function tep_session_start() {
    global $_GET, $_POST, $HTTP_COOKIE_VARS;

    $sane_session_id = true;

    if (isset($_GET[tep_session_name()])) {
      if (preg_match('/^[a-zA-Z0-9]+$/', $_GET[tep_session_name()]) == false) {
        unset($_GET[tep_session_name()]);

        $sane_session_id = false;
      }
    } elseif (isset($_POST[tep_session_name()])) {
      if (preg_match('/^[a-zA-Z0-9]+$/', $_POST[tep_session_name()]) == false) {
        unset($_POST[tep_session_name()]);

        $sane_session_id = false;
      }
    } elseif (isset($HTTP_COOKIE_VARS[tep_session_name()])) {
      if (preg_match('/^[a-zA-Z0-9]+$/', $HTTP_COOKIE_VARS[tep_session_name()]) == false) {
        $session_data = session_get_cookie_params();

        setcookie(tep_session_name(), '', time()-42000, $session_data['path'], $session_data['domain']);

        $sane_session_id = false;
      }
    }

    if ($sane_session_id == false) {
      tep_redirect(tep_href_link(FILENAME_DEFAULT, '', 'NONSSL', false));
    }

    return session_start();
  }
Exemple #28
0
 function start_session($sessionName = 'PHPSESSID', $secure = false)
 {
     // Make sure the session cookie is not accessable via javascript.
     $httponly = true;
     // Hash algorithm to use for the sessionid. (use hash_algos() to get a list of available hashes.)
     $session_hash = 'sha512';
     // Check if hash is available
     if (in_array($session_hash, hash_algos())) {
         // Set the has function.
         ini_set('session.hash_function', $session_hash);
     }
     // 많은 해시의 문자 비트.
     // The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ",").
     ini_set('session.hash_bits_per_character', 5);
     // 쿠키 만이 아닌 URL 변수를 사용하여 세션을 강제로.
     ini_set('session.use_only_cookies', 1);
     // 세션 쿠키의 매개 변수를 가져옴
     $cookieParams = session_get_cookie_params();
     // 매개 변수를 설정합니다
     session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
     // 세션을 시작
     session_name($sessionName);
     // Now we cat start the session
     session_start();
     /**
      * TODO::
      * 이 줄은 세션을 다시 생성하고 기존 하나를 삭제합니다.
      * 또한 데이터베이스에 새로운 암호화 키를 생성한다.
      */
     // session_regenerate_id ( true );
 }
Exemple #29
0
function adodb_session_regenerate_id()
{
    $conn =& ADODB_Session::_conn();
    if (!$conn) {
        return false;
    }
    $old_id = session_id();
    if (function_exists('session_regenerate_id')) {
        session_regenerate_id();
    } else {
        session_id(md5(uniqid(rand(), true)));
        $ck = session_get_cookie_params();
        setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
        //@session_start();
    }
    $new_id = session_id();
    $ok =& $conn->Execute('UPDATE ' . ADODB_Session::table() . ' SET sesskey=' . $conn->qstr($new_id) . ' WHERE sesskey=' . $conn->qstr($old_id));
    /* it is possible that the update statement fails due to a collision */
    if (!$ok) {
        session_id($old_id);
        if (empty($ck)) {
            $ck = session_get_cookie_params();
        }
        setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
        return false;
    }
    return true;
}
Exemple #30
0
/**
 * Create Cleaner settings form.
 *
 * @return array
 *   Form of the cleaner settings page.
 */
function hook_cleaner_settings()
{
    // Add CSS to the admin settings page.
    drupal_add_css(drupal_get_path('module', 'cleaner') . '/cleaner.css');
    $form = array();
    $yes_no = array(t('No'), t('Yes'));
    $inline = array('class' => array('container-inline'));
    $interval = array(0 => t('Every time')) + Cleaner::$intervals;
    $form['cleaner_cron'] = array('#type' => 'radios', '#title' => t('Run interval'), '#options' => $interval, '#default_value' => variable_get('cleaner_cron', 3600), '#description' => t('This is how often the options below will occur. The actions will occur on the next Cron run after this interval expires. "Every time" means on every Cron run.'), '#attributes' => $inline);
    $form['cleaner_clear_cache'] = array('#type' => 'radios', '#options' => $yes_no, '#title' => t('Clean up cache'), '#default_value' => variable_get('cleaner_clear_cache', 0), '#description' => Cleaner::cleanerGetCacheTablesTable(), '#attributes' => $inline);
    $form['cleaner_empty_watchdog'] = array('#type' => 'radios', '#options' => $yes_no, '#title' => t('Clean up Watchdog'), '#default_value' => variable_get('cleaner_empty_watchdog', 0), '#description' => t('There is a standard setting for controlling Watchdog contents. This is more useful for test sites.'), '#attributes' => $inline);
    $cookie = session_get_cookie_params();
    $select = db_select('sessions', 's')->fields('s', array('timestamp'))->condition('timestamp', REQUEST_TIME - $cookie['lifetime'], '<');
    $count = $select->execute()->rowCount();
    $form['cleaner_clean_sessions'] = array('#type' => 'radios', '#options' => $yes_no, '#title' => t('Clean up Sessions table'), '#default_value' => variable_get('cleaner_clean_sessions', 0), '#description' => t('The sessions table can quickly become full with old, abandoned sessions. This will delete all sessions older than @interval (as set by your site administrator). There are currently @count such sessions.', array('@interval' => format_interval($cookie['lifetime']), '@count' => $count)), '#attributes' => $inline);
    $form['cleaner_clean_cssdir'] = array('#type' => 'radios', '#options' => $yes_no, '#title' => t('Clean up CSS files'), '#default_value' => variable_get('cleaner_clean_cssdir', 0), '#description' => t('The CSS directory can become full with stale and outdated cache files.  This will delete all CSS cache files but the latest.'), '#attributes' => $inline);
    $form['cleaner_clean_jsdir'] = array('#type' => 'radios', '#options' => $yes_no, '#title' => t('Clean up JS files'), '#default_value' => variable_get('cleaner_clean_jsdir', 0), '#description' => t('The JS directory can become full with stale and outdated cache files.  This will delete all JS cache files but the latest.'), '#attributes' => $inline);
    // We can only offer OPTIMIZE to MySQL users.
    if (db_driver() == 'mysql') {
        $form['cleaner_optimize_db'] = array('#type' => 'radios', '#options' => $yes_no + array('2' => 'Local only'), '#title' => t('Optimize tables with "overhead" space'), '#default_value' => variable_get('cleaner_optimize_db', 0), '#description' => t('The module will compress (optimize) all database tables with unused space. <strong>NOTE</strong>: During an optimization, the table will locked against any other activity; on a high vloume site, this may be undesirable. "Local only" means do not replicate the optimization (if it is being done).'), '#attributes' => $inline);
    } else {
        // If not MySQL, delete(reset) the variable.
        variable_del('cleaner_optimize_db');
    }
    return array('cleaner' => $form);
}