Добрый день. Я с php ничего общего не имею. Немного html баловался в молодости, кое какие принципы и php знаю.Что позволяет мне хоть немного без страха лезть в файловый менеджер и что либо править.
Собственно корпоративный сайт работал долгое время без сбоев и тут вышли распространенная ошибки:
Кодировка у сайта полностью сбилась — крокозябры какие-то. Но это быстро решилось сменой кодировки в панели управления хостинга.
А вот эти ошибки так и остались, с ними в админку не пускает.
Что я сделал? как советовали в интернете — первое, что необходимо сделать это проверить кодировки указанных в ошибке файлов и поставить UTF без BOM. Сказано — сделано, полностью перезалил новый файлы. Ошибка не ушла.
Еще советуют поставить session_start() в самое начало, но что-то при данных попытках сайт у меня вообще ложился)
Собственно код session.php
* @package Joomla.Platform
* @copyright Copyright (C) 2005 — 2014 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
* Class for managing HTTP sessions
* Provides access to session-state values as well as session-level
* settings and lifetime management methods.
* Based on the standard PHP session handling mechanism it provides
* more advanced features such as expire timeouts.
* @package Joomla.Platform
class JSession implements IteratorAggregate
* One of ‘inactive’|’active’|’expired’|’destroyed’|’error’
* @see JSession::getState()
protected $_state = ‘inactive’;
* Maximum age of unused session in minutes
* The session store object.
protected $_store = null;
* List of checks that will be done.
protected $_security = array(‘fix_browser’);
* Force cookies to be SSL only
protected $_force_ssl = false;
* JSession instances container.
protected static $instance;
* The type of storage for the session.
* Holds the JInput object
* Holds the event dispatcher object
private $_dispatcher = null;
* @param string $store The type of storage for the session.
* @param array $options Optional parameters
public function __construct($store = ‘none’, array $options = array())
// Need to destroy any existing sessions started with session.auto_start
// Disable transparent sid support
ini_set(‘session.use_trans_sid’, ‘0’);
// Only allow the session ID to come from cookies and nothing else.
ini_set(‘session.use_only_cookies’, ‘1’);
$this->_store = JSessionStorage::getInstance($store, $options);
$this->storeName = $store;
$this->_setOptions($options);
$this->_setCookieParams();
$this->_state = ‘inactive’;
* Magic method to get read-only access to properties.
* @param string $name Name of property to retrieve
* @return mixed The value of the property
public function __get($name)
if ($name === ‘storeName’)
if ($name === ‘state’ || $name === ‘expire’)
* Returns the global Session object, only creating it
* if it doesn’t already exist.
* @param string $handler The type of session handler.
* @param array $options An array of configuration options.
* @return JSession The Session object.
public static function getInstance($handler, $options)
self::$instance = new JSession($handler, $options);
* Get current state of session
* @return string The session state
public function getState()
* Get expiration time in minutes
* @return integer The session expiration time in minutes
public function getExpire()
* Get a session token, if a token isn’t set yet one will be generated.
* Tokens are used to secure forms from spamming attacks. Once a token
* has been generated the system will check the post request to see if
* it is present, if not it will invalidate the session.
* @param boolean $forceNew If true, force a new token to be created
* @return string The session token
public function getToken($forceNew = false)
$token = $this->get(‘session.token’);
if ($token === null || $forceNew)
$token = $this->_createToken(12);
$this->set(‘session.token’, $token);
* Method to determine if a token exists in the session. If not the
* session will be set to expired
* @param string $tCheck Hashed token to be verified
* @param boolean $forceExpire If true, expires the session
public function hasToken($tCheck, $forceExpire = true)
// Check if a token exists in the session
$tStored = $this->get(‘session.token’);
if (($tStored !== $tCheck))
$this->_state = ‘expired’;
* Method to determine a hash for anti-spoofing variable names
* @param boolean $forceNew If true, force a new token to be created
* @return string Hashed var name
public static function getFormToken($forceNew = false)
$user = JFactory::getUser();
$session = JFactory::getSession();
// TODO: Decouple from legacy JApplication class.
$hash = JApplication::getHash($user->get(‘id’, 0) . $session->getToken($forceNew));
$hash = md5(JFactory::getApplication()->get(‘secret’) . $user->get(‘id’, 0) . $session->getToken($forceNew));
* Retrieve an external iterator.
* @return ArrayIterator Return an ArrayIterator of $_SESSION.
public function getIterator()
return new ArrayIterator($_SESSION);
* Checks for a form token in the request.
* Use in conjunction with JHtml::_(‘form.token’) or JSession::getFormToken.
* @param string $method The request method in which to look for the token key.
* @return boolean True if found and valid, false otherwise.
public static function checkToken($method = ‘post’)
$token = self::getFormToken();
$app = JFactory::getApplication();
if (!$app->input->$method->get($token, », ‘alnum’))
$session = JFactory::getSession();
// Redirect to login screen.
$app->enqueueMessage(JText::_(‘JLIB_ENVIRONMENT_SESSION_EXPIRED’), ‘warning’);
$app->redirect(JRoute::_(‘index.php’));
* @return string The session name
public function getName()
if ($this->_state === ‘destroyed’)
* @return string The session name
if ($this->_state === ‘destroyed’)
* Get the session handlers
* @return array An array of available session handlers
public static function getStores()
// Get an iterator and loop trough the driver classes.
$iterator = new DirectoryIterator(__DIR__ . ‘/storage’);
/* @type $file DirectoryIterator */
foreach ($iterator as $file)
$fileName = $file->getFilename();
// Only load for php files.
if (!$file->isFile() || $file->getExtension() != ‘php’)
// Derive the class name from the type.
// If the class doesn’t exist we have nothing left to do but look at the next type. We did our best.
// Sweet! Our class exists, so now we just need to know if it passes its test method.
if ($class::isSupported())
// Connector names should not have file extensions.
* Shorthand to check if the session is active
public function isActive()
return (bool) ($this->_state == ‘active’);
* Check whether this session is currently created
* @return boolean True on success.
$counter = $this->get(‘session.counter’);
return (bool) ($counter === 1);
* Check whether this session is currently created
* @param JInput $input JInput object for the session to use.
* @param JEventDispatcher $dispatcher Dispatcher object for the session to use.
public function initialise(JInput $input, JEventDispatcher $dispatcher = null)
$this->_dispatcher = $dispatcher;
* Get data from the session store
* @param string $name Name of a variable
* @param mixed $default Default value of a variable if not set
* @param string $namespace Namespace to use, default to ‘default’
* @return mixed Value of a variable
public function get($name, $default = null, $namespace = ‘default’)
// Add prefix to namespace to avoid collisions
$namespace = ‘__’ . $namespace;
if ($this->_state === ‘destroyed’)
// @TODO :: generated error here
if (isset($_SESSION[$namespace][$name]))
return $_SESSION[$namespace][$name];
* Set data into the session store.
* @param string $name Name of a variable.
* @param mixed $value Value of a variable.
* @param string $namespace Namespace to use, default to ‘default’.
* @return mixed Old value of a variable.
public function set($name, $value = null, $namespace = ‘default’)
// Add prefix to namespace to avoid collisions
$namespace = ‘__’ . $namespace;
if ($this->_state !== ‘active’)
// @TODO :: generated error here
$old = isset($_SESSION[$namespace][$name]) ? $_SESSION[$namespace][$name] : null;
unset($_SESSION[$namespace][$name]);
$_SESSION[$namespace][$name] = $value;
* Check whether data exists in the session store
* @param string $name Name of variable
* @param string $namespace Namespace to use, default to ‘default’
* @return boolean True if the variable exists
public function has($name, $namespace = ‘default’)
// Add prefix to namespace to avoid collisions.
$namespace = ‘__’ . $namespace;
if ($this->_state !== ‘active’)
// @TODO :: generated error here
return isset($_SESSION[$namespace][$name]);
* Unset data from the session store
* @param string $name Name of variable
* @param string $namespace Namespace to use, default to ‘default’
* @return mixed The value from session or NULL if not set
public function clear($name, $namespace = ‘default’)
// Add prefix to namespace to avoid collisions
$namespace = ‘__’ . $namespace;
if ($this->_state !== ‘active’)
// @TODO :: generated error here
if (isset($_SESSION[$namespace][$name]))
$value = $_SESSION[$namespace][$name];
unset($_SESSION[$namespace][$name]);
if ($this->_state === ‘active’)
$this->_state = ‘active’;
// Initialise the session
// Perform security checks
if ($this->_dispatcher instanceof JEventDispatcher)
$this->_dispatcher->trigger(‘onAfterSessionStart’);
* Creates a session (or resumes the current one based on the state of the session)
* @return boolean true on success
protected function _start()
// Start session if not started
if ($this->_state === ‘restart’)
// Get the JInputCookie object
$cookie = $this->_input->cookie;
if (is_null($cookie->get($session_name)))
$session_clean = $this->_input->get($session_name, false, ‘string’);
$cookie->set($session_name, », time() — 3600);
* Write and Close handlers are called after destructing objects since PHP 5.0.5.
* Thus destructors can use sessions but session handler can’t use objects.
* So we are moving session closure before destructing objects.
* Replace with session_register_shutdown() when dropping compatibility with PHP 5.3
* Frees all session variables and destroys all data registered to a session
* This method resets the $_SESSION variable and destroys all of the data associated
* with the current session in its storage (file or DB). It forces new session to be
* started after this method is called. It does not unset the session cookie.
* @return boolean True on success
public function destroy()
// Session was already destroyed
if ($this->_state === ‘destroyed’)
* In order to kill the session altogether, such as to log the user out, the session id
* must also be unset. If a cookie is used to propagate the session id (default behavior),
* then the session cookie must be deleted.
$config = JFactory::getConfig();
$cookie_domain = $config->get(‘cookie_domain’, »);
$cookie_path = $config->get(‘cookie_path’, ‘/’);
$this->_state = ‘destroyed’;
* Restart an expired or locked session.
* @return boolean True on success
* @see JSession::destroy()
public function restart()
if ($this->_state !== ‘destroyed’)
// @TODO :: generated error here
// Re-register the session handler after a session has been destroyed, to avoid PHP bug
$this->_store->register();
$this->_state = ‘restart’;
$this->_state = ‘active’;
* Create a new session and copy variables from the old one
* @return boolean $result true on success
if ($this->_state !== ‘active’)
// @TODO :: generated error here
// Re-register the session store after a session has been destroyed, to avoid PHP bug
$this->_store->register();
// Restart session with new id
* Writes session data and ends session
* Session data is usually stored after your script terminated without the need
* to call JSession::close(), but as session data is locked to prevent concurrent
* writes only one script may operate on a session at any time. When using
* framesets together with sessions you will experience the frames loading one
* by one due to this locking. You can reduce the time needed to load all the
* frames by ending the session as soon as all changes to session variables are
* @see session_write_close()
* Set session cookie parameters
protected function _setCookieParams()
$cookie[‘secure’] = true;
$config = JFactory::getConfig();
if ($config->get(‘cookie_domain’, ») != »)
$cookie[‘domain’] = $config->get(‘cookie_domain’);
if ($config->get(‘cookie_path’, ») != »)
$cookie[‘path’] = $config->get(‘cookie_path’);
* @param integer $length Length of string
* @return string Generated token
protected function _createToken($length = 32)
static $chars = ‘0123456789abcdef’;
for ($i = 0; $i < $length; ++$i)
$token .= $chars[(rand(0, $max))];
return md5($token . $name);
* Set counter of session usage
* @return boolean True on success
protected function _setCounter()
$counter = $this->get(‘session.counter’, 0);
$this->set(‘session.counter’, $counter);
* @return boolean True on success
protected function _setTimers()
if (!$this->has(‘session.timer.start’))
$this->set(‘session.timer.start’, $start);
$this->set(‘session.timer.last’, $start);
$this->set(‘session.timer.now’, $start);
$this->set(‘session.timer.last’, $this->get(‘session.timer.now’));
$this->set(‘session.timer.now’, time());
* Set additional session options
* @param array $options List of parameter
* @return boolean True on success
protected function _setOptions(array $options)
if (isset($options[‘name’]))
if (isset($options[‘id’]))
if (isset($options[‘expire’]))
$this->_expire = $options[‘expire’];
if (isset($options[‘security’]))
$this->_security = explode(‘,’, $options[‘security’]);
if (isset($options[‘force_ssl’]))
$this->_force_ssl = (bool) $options[‘force_ssl’];
// Sync the session maxlifetime
ini_set(‘session.gc_maxlifetime’, $this->_expire);
* Do some checks for security reason
* — timeout check (expire)
* If one check failed, session data has to be cleaned.
* @param boolean $restart Reactivate session
* @return boolean True on success
* @see http://shiflett.org/articles/the-truth-about-sessions
protected function _validate($restart = false)
// Allow to restart a session
$this->_state = ‘active’;
$this->set(‘session.client.address’, null);
$this->set(‘session.client.forwarded’, null);
$this->set(‘session.client.browser’, null);
$this->set(‘session.token’, null);
// Check if session has expired
$curTime = $this->get(‘session.timer.now’, 0);
$maxTime = $this->get(‘session.timer.last’, 0) + $this->_expire;
// Empty session variables
$this->_state = ‘expired’;
// Record proxy forwarded for in the session in case we need it later
if (isset($_SERVER[‘HTTP_X_FORWARDED_FOR’]))
$this->set(‘session.client.forwarded’, $_SERVER[‘HTTP_X_FORWARDED_FOR’]);
// Check for client address
if (in_array(‘fix_adress’, $this->_security) && isset($_SERVER[‘REMOTE_ADDR’]))
$ip = $this->get(‘session.client.address’);
$this->set(‘session.client.address’, $_SERVER[‘REMOTE_ADDR’]);
elseif ($_SERVER[‘REMOTE_ADDR’] !== $ip)
// Check for clients browser
if (in_array(‘fix_browser’, $this->_security) && isset($_SERVER[‘HTTP_USER_AGENT’]))
$browser = $this->get(‘session.client.browser’);
$this->set(‘session.client.browser’, $_SERVER[‘HTTP_USER_AGENT’]);
elseif ($_SERVER[‘HTTP_USER_AGENT’] !== $browser)
// @todo remove code: $this->_state = ‘error’;
// @todo remove code: return false;
кто что может подсказать?
Подсказка от модератора:
Любой код или текст конфигурации пишите между тегом [code=php] и [/code].
Используйте отступы в коде для форматирования текста.
Это помогает быстрее понять вас, увеличивает шанс на получение ответа.
Что выделять? Например: PHP, HTML, CSS, JavaScript, SQL, XML, .htaccess, ini, регулярные выражения, код шаблонизаторов, любая другая разметка, результаты array/object dump и т. д.
При просмотре веб-сайта, который управляется базой данных, требует входа в систему или является защищенным, вы можете увидеть ошибку «Session Expired» или «Session Is Expired». Причины этих сообщений об ошибках подробно описаны в следующих разделах.
- Бездействие — если вы ничего не делали на странице в течение установленного промежутка времени (часто 10-30 минут), сервер истечет время вашего сеанса. Таймеры неактивности были созданы по соображениям безопасности и для повышения общей скорости веб-страницы. Другими словами, если вы просматривали страницу и вставали и уходили, переходили на ланч или начинали просматривать другие страницы, когда вы вернетесь, вам потребуется снова войти в систему и создать новый сеанс.
- Неправильная дата или время — убедитесь, что на вашем компьютере правильно установлены дата и время.
- Куки — Если вы просматриваете анонимно или в вашем браузере не включены куки, это приводит к сбою многих сеансов. Убедитесь, что ваши интернет-куки включены.
- Брандмауэр или прокси-сервер. Если вы подключаетесь к Интернету через брандмауэр или через прокси-сервер, брандмауэр или прокси-сервер может ограничивать или запрещать создание сеанса.
- Другая проблема, связанная с сайтом. Если эта проблема возникает только на определенном сайте, и вы не сталкиваетесь ни с одной из вышеперечисленных проблем, возможно, проблема с сайтом. Свяжитесь с компанией или веб-мастером, чтобы убедиться, что проблема не на их стороне.
Могу ли я увеличить продолжительность сеанса?
Продолжительность сеанса веб-страницы измеряется на сервере, а не на вашем компьютере. Поэтому вы не можете изменить оставшееся время веб-сеанса.
Я попытался сделать простую систему входа в систему, и я серьезно застрял. Проблема с сессиями. Когда я нажимаю кнопку входа, я перенаправлен на страницу входа. Теперь, насколько я мог видеть, сеанс запускается в странице входа в систему .session_id () дает некоторое число.
Но защищенная страница показывает NULL. Как начать сеанс на защищенной странице? Я попытался реализовать код некоторых примеров — все еще перенаправляет на страницу входа. Я попытался с новой пустой страницей, только форма на странице, но с той же БД и все еще перенаправляет на страницу входа.
Это страница входа
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require('dbcon.php');
if (isset($_POST['email']) && ($_POST['password'])) {
$e = mysqli_real_escape_string($dbcon, $_POST['email']);
$p = mysqli_real_escape_string($dbcon, $_POST['password']);
$q = "SELECT uid,mail,psword,unm FROM pics WHERE (mail='$e' AND psword=SHA1('$p'))";
$result = mysqli_query($dbcon,$q);
if(mysqli_num_rows($result) == 1){
session_start();
$uid = mysqli_fetch_array ($result, MYSQLI_ASSOC);
$_SESSION['uid'] = $uid['uid'];
header("location: members.php");
exit();
mysqli_free_result($result);
mysqli_close($dbcon);
}else{
echo 'no match';
}
}else{
echo 'Empty fields...';
}
}
?>
И это в верхней части «защищенной» страницы
<?php
session_start();
if(!isset($_SESSION['uid'])){
header("Location:index.php");
}
?>
информация о сеансе
session
Session Support enabled
Registered save handlers files user
Registered serializer handlers php_serialize php php_binary wddx
Directive Local Value Master Value
session.auto_start Off Off
session.cache_expire 180 180
session.cache_limiter nocache nocache
session.cookie_domain no value no value
session.cookie_httponly Off Off
session.cookie_lifetime 0 0
session.cookie_path / /
session.cookie_secure Off Off
session.entropy_file no value no value
session.entropy_length 0 0
session.gc_divisor 1000 1000
session.gc_maxlifetime 1440 1440
session.gc_probability 1 1
session.hash_bits_per_character 5 5
session.hash_function 0 0
session.name PHPSESSID PHPSESSID
session.referer_check no value no value
session.save_handler files files
session.save_path C:xampptmp C:xampptmp
session.serialize_handler php php
session.upload_progress.cleanup On On
session.upload_progress.enabled On On
session.upload_progress.freq 1% 1%
session.upload_progress.min_freq 1 1
session.upload_progress.name PHP_SESSION_UPLOAD_PROGRESS PHP_SESSION_UPLOAD_PROGRESS
session.upload_progress.prefix upload_progress_ upload_progress_
session.use_cookies On On
session.use_only_cookies On On
session.use_strict_mode Off Off
session.use_trans_sid 0 0
0
Решение
Предположения, которые я сделал и которые не сформулированы в Вопросе:
-
Эти данные формы представлены с
POST
введите и с правильным набором символов (такu
этоu
этоu
) -
То, что весь код, показанный в вопросе, находится в файлах, на которые есть ссылки в заголовках, и не содержится во включенных и других «спрятанных углах».
Некоторые улучшения кода
<?php
session_start(); //at the start.
error_reporting(E_ALL); //as suggested by others add error logging
ini_set('display_errors',1); //and debugging to tell you info.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require 'dbcon.php'; //no need for brackets here.
if (!empty($_POST['email']) && !empty($_POST['password'])) {
// you had a syntax error here. Also use empty() rather than
// isset as POSTED forms will still send the data containers
// even if it contains nothing.
$e = mysqli_real_escape_string($dbcon, $_POST['email']);
$p = mysqli_real_escape_string($dbcon, $_POST['password']);
$q = "SELECT uid,mail,psword,unm FROM pics WHERE mail='$e' AND psword=SHA1('$p')"; //no need for brackets here.
$result = mysqli_query($dbcon,$q);
if(mysqli_num_rows($result) == 1){
$uid = mysqli_fetch_array ($result, MYSQLI_ASSOC);
if(is_array($uid) && count($uid) > 0){
//added a further debug qualifier here
// to check that your SQL result is as expected.
$_SESSION['uid'] = $uid['uid'];
mysqli_free_result($result); //These occur AFTER the
mysqli_close($dbcon); // exit statement which stops the script.
//so put them before hand. but it's pretty worthless as
//mysqli will stop the connection anyway unless
//specifically told otherwise.
header("location: members.php");
exit();
}
else {
die("your SQL returned an empty result");
}
}else{
echo 'no match';
}
}else{
echo 'Empty fields...';
}
}
// removed PHP closing marker. Unneeded.
Как примечание, почему вы выбираете 4 значения из таблицы, когда используете только одно значение?
Страница назначения
Итак, теперь вы заверили нас, что значения извлекаются с помощью SQL ok и сохраняются в SESSION
Итак, проблема в том, чтобы найти сеанс на странице назначения?
Сначала запустите сессию:
Затем, как уже говорили другие, — журнал ошибок и отладка:
тогда посмотрим что имеет был передан обработчику сеанса:
session_start(); //always at the start!!!
error_reporting(E_ALL); //always use for error reporting in development
ini_set('display_errors',1); //always!!!
print_r($_SESSION);
Если здесь нет ошибок, вам нужно вернуться на страницу входа и проверить правильность сохранения сеансов, поэтому:
$uid = mysqli_fetch_array ($result, MYSQLI_ASSOC);
$_SESSION['uid'] = $uid['uid'];
$_SESSION['sausages'] = "roasted";
...
header("location: members.php");
exit();
А затем вернитесь и посмотрите, появляется ли эта статическая переменная строка на вашем members.php
страница,
-
Если это так, то это показывает, что ваш запрос SQL а не ваша сессия является недействительным и терпит неудачу, и я не буду вдаваться в подробности, но достаточно сказать, что сессия не является проблемой. Вероятная ошибка: вы не сохраняете хешированное значение (
SHA1
) правильно в вашей базе данных. Но нам нужна дополнительная информация, чтобы предоставить конкретную помощь в случае, если это ошибка SQL. -
Если он не появляется, то это указывает на проблему сеанса или проблему с обработкой файлов, в основном вам необходимо иметь четкий путь к коду, в котором находится код в структуре файла, — это «защищенный» код страницы, который вы фактически показали нам в страница, на которую есть ссылка в заголовке, и находится ли она в том же каталоге, что и страница входа (а не
mod_rewrite
джибджаг и т. д.)
Скажите мне, что это за свет, когда вы точно определяете, где начинается ваша проблема.
В других заметках стоит отметить, что ваша система паролей не соответствует качеству продукции, поэтому следует использовать другой подход. Пожалуйста, изучите StackOverflow.
РЕДАКТИРОВАТЬ:
Детали сессии:
- очередь
session.cookie_httponly
вon
, - проверьте, что папки сессий хранятся в (
C:xampptmp
) имеет все настройки чтения, записи и выполнения (chmod 0777
). - менять
session.use_strict_mode
вon
, - Задавать
session.auto_start
вon
,
Хотя я должен признать, что, кроме того, что я абсолютно уверен, что PHP имеет разрешение на чтение и запись в указанный каталог сеанса, ничто в информации о вашем сеансе не выделяется мне как возможная причина.
Есть ли у вас какие-либо ошибки / предупреждения в журналах вашего сервера (программа, которая запускает PHP на вашем компьютере)?
Вы можете найти хороший объяснение chmod здесь.
ЭТА ПОЧТА может быть вам очень поможет.
1
Другие решения
Это заголовок строки («location: members.php»); за работой?
Я не вижу необходимости в следующих строках:
exit();
mysqli_free_result($result);
mysqli_close($dbcon);
Потому что ваша страница уже была перенаправлена.
Теперь, что именно вы написали на странице members.php?
Если моя идея верна, вы включили эту защищенную страницу поверх members.php?
0
Я добавил html5, открыл новый проект и начал добавлять html-файлы один за другим. У меня была резервная копия сайта непосредственно перед тем, как я начал кодировать логин. Затем я скопировал код php. Затем файлы css и js. Пока логин работает так же, как и с тем же кодом, если я не изменяю имя папки. Надеюсь, что так и останется. Спасибо за ваше время и помощь. Я ценю это.
0
Are you getting the Laravel error 419 session expired during a post request?
This occurs due to CSRF token verification failure, misconfigured cache, permissions, improper session settings, etc.
At Bobcares, we fix Laravel errors, as a part of our Server Management Services.
Today, let’s have a look into the session expired error. We’ll also see how our Support Engineers fix it.
Laravel Error: 419 session expired
Laravel is a web development framework. It allows customizing configuration. And the user/developer can create a .env file for this purpose.
By default, Laravel is an HTTP driven application. The session provides ways to store information. The available options are files, cookie, database, Memcached or Redis, and array.
This error shows up when a user submits a post request. The error in front-end appears as,
And, in the command line, the error appears as,
419 Sorry, your session has expired. Please refresh and try again.
Many reasons can lead to session expired error. The most obvious reasons are CSRF token failure, cache, permissions, improper session settings.
How we fix the Laravel error 419 session expired?
Our Support Engineers with expertise over a decade in Server Administration fixes Laravel errors. Let’s see the common causes and how we fix it.
1. CSRF token verification failure
The most common reason for the 419 error is CSRF token failure. Cross-site request forgery token is a unique, encrypted value generated by the server.
Laravel generates a CSRF token for each user session. The token verifies the user by requesting the application.
So always include a CSRF token in the HTML form to validate the user request.
The VerifyCsrfToken middleware automatically crosses checks the token in the request to the token stored in the session.
In addition to CSRF token verification, the VerifyCsrfToken middleware also checks the X-CSRF-TOKEN request header.
So, we store the token in the HTML meta tag. Then a library like jQuery can automatically add a token to all request headers. Therefore to fix the CSRF token failure we check the token in the application.
2. Session expired error due to cache
Sometimes, the cache can also lead to session expired error in front-end. This can be both the server cache and browser cache. So, our Support Engineers clear the server cache using
php artisan cache:clear
If this does not fix the error, we ask the customer to clear the browser cache. Many times this fixes the error.
3. Laravel file and folder permissions
Similarly, improper file or folder permission can also lead to errors. Usually, web servers need write-permissions on the Laravel folders storage and vendor. Also, session storage needs write-permission. So, our Support Engineers give permissions as,
chmod -R 755 storage
chmod -R 755 vendor
chmod -R 644 bootstrap/caches
Mostly, this fixes the error.
4. Laravel session setting
Last but not least, session settings can also cause a 419 error. The app/config/session.php is the session config file. Our Experts check the session settings in this file. Hence we correct if there is an error. We always check for a few important parameters – domain and secure.
'domain' => env('SESSION_DOMAIN', null),
'secure' => env('SESSION_SECURE_COOKIE', false),
// in case of cookie
These step by step approach fixes the error and make Laravel working again.
[Need assistance in fixing Laravel errors? – Our Experts are available 24/7.]
Conclusion
In short, the Laravel error 419 session expired occur due to many reasons like CSRF token failure, wrong cache, permissions, improper session settings, etc. Today, we saw how our Support Engineers fix this error.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
A clear and concise description of what works not as it is supposed to.
How to reproduce
Executing a query will periodically throw an exception
-
Which ClickHouse server version to use
-
version 20.5.4.40
-
Queries to run that lead to unexpected result
SELECT SUM(num) from (select count(1) as num from default.device_param_raw UNION ALL select count(1) as num from default.live_weather UNION ALL select count(1) as num from default.forecast_hourly_weather UNION ALL select count(1) as num from default.zjk_air_quality_pollution_hourly_data UNION ALL select count(1) as num from default.zjk_fire_device_raw_data UNION ALL select count(1) as num from default.zjk_air_quality_device_raw_data) as a;
Expected behavior
SUM(num)
A clear and concise description of what you expected to happen.
Error message and/or stacktrace
user server
ru.yandex.clickhouse.except.ClickHouseException: ClickHouse exception, code: 999, host: 10.80.43.71, port: 8123; Code: 999, e.displayText() = DB::Exception: Received from p2mysql1:9000. DB::Exception: Session expired (Session expired). (version 20.5.4.40)
at ru.yandex.clickhouse.except.ClickHouseExceptionSpecifier.specify(ClickHouseExceptionSpecifier.java:58)
at ru.yandex.clickhouse.except.ClickHouseExceptionSpecifier.specify(ClickHouseExceptionSpecifier.java:28)
at ru.yandex.clickhouse.ClickHouseStatementImpl.checkForErrorAndThrow(ClickHouseStatementImpl.java:875)
at ru.yandex.clickhouse.ClickHouseStatementImpl.getInputStream(ClickHouseStatementImpl.java:616)
at ru.yandex.clickhouse.ClickHouseStatementImpl.executeQuery(ClickHouseStatementImpl.java:117)
at ru.yandex.clickhouse.ClickHouseStatementImpl.executeQuery(ClickHouseStatementImpl.java:100)
at ru.yandex.clickhouse.ClickHouseStatementImpl.executeQuery(ClickHouseStatementImpl.java:95)
at ru.yandex.clickhouse.ClickHouseStatementImpl.executeQuery(ClickHouseStatementImpl.java:90)
at com.chinaentropy.sensorcloud.data_intergration.utils.CkHouseConnection.distributeQuery(CkHouseConnection.java:53)
at com.chinaentropy.sensorcloud.data_intergration.service.impl.SystemFrontPageServiceImpl.cronClean(SystemFrontPageServiceImpl.java:283)
at sun.reflect.GeneratedMethodAccessor107.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.Throwable: Code: 999, e.displayText() = DB::Exception: Received from p2mysql1:9000. DB::Exception: Session expired (Session expired). (version 20.5.4.40)
at ru.yandex.clickhouse.except.ClickHouseExceptionSpecifier.specify(ClickHouseExceptionSpecifier.java:53)
... 21 more
the clickhouse server
2021.08.30 13:42:38.869538 [ 2507 ] {} zkutil::EphemeralNodeHolder::~EphemeralNodeHolder(): Code: 999, e.displayText() = Coordination::Exception: Session expired (Session expired), Stack trace (when copyingthis message, always include the lines below):
- Poco::Exception::Exception(std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator > const&, int) @ 0xcc3083c in /usr/bin/clickhouse
- DB::Exception::Exception(std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator > const&, int) @ 0x5a54619 in /usr/bin/clickhouse
- Coordination::Exception::Exception(std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator > const&, Coordination::Error, int) @ 0xa9d3a64 in /usr/bin/clickhouse
- Coordination::Exception::Exception(std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator > const&, Coordination::Error) @ 0xa9d40fa in /usr/bin/clickhouse
- ? @ 0x57d9a24 in /usr/bin/clickhouse
- Coordination::ZooKeeper::remove(std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator > const&, int, std::__1::function<void (Coordination::RemoveResponse const&)>) @ 0xa9ec61c in /usr/bin/clickhouse
- zkutil::ZooKeeper::tryRemove(std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator > const&, int) @ 0xa9da2e7 in /usr/bin/clickhouse
- std::__1::__shared_ptr_emplace<zkutil::EphemeralNodeHolder, std::__1::allocatorzkutil::EphemeralNodeHolder >::__on_zero_shared() @ 0x5b41a4a in /usr/bin/clickhouse
- DB::ReplicatedMergeTreeRestartingThread::partialShutdown() @ 0xa2af09a in /usr/bin/clickhouse
- DB::ReplicatedMergeTreeRestartingThread::run() @ 0xa2b410e in /usr/bin/clickhouse
- DB::BackgroundSchedulePoolTaskInfo::execute() @ 0xa562f72 in /usr/bin/clickhouse
- DB::BackgroundSchedulePool::threadFunction() @ 0xa56339a in /usr/bin/clickhouse
- ? @ 0xa56349f in /usr/bin/clickhouse
- ThreadPoolImplstd::__1::thread::worker(std::__1::__list_iterator<std::__1::thread, void*>) @ 0x5a5e12d in /usr/bin/clickhouse
- ? @ 0x5a5c7af in /usr/bin/clickhouse
- start_thread @ 0x7ea5 in /usr/lib64/libpthread-2.17.so
- clone @ 0xfe96d in /usr/lib64/libc-2.17.so
(version 20.5.4.40)
If applicable, add screenshots to help explain your problem.
Additional context
Add any other context about the problem here.
Are you currently seeing a “Your session has Expired” message on your Upsell & Downsell pages?
This error message is usually seen only on the Upsell & Downsell pages of the CartFlows. This message means that the Session which was set on the checkout page has expired on the Upsell or Downsell pages.
If you are getting the session expired error message on the Checkout page of the CartFlows, then it means that the CartFlows session cookie ( cartflows_session_ ) or the WooCommerce’s Session cookie is not getting registered on the CartFlows.
Usually, this happens when the CartFlows pages are cached at the server end or at the local end. To fix this, you need to clear the cache and exclude the CartFlows Checkout pages from the server-side or local cache.
Quick Tip: If you want to avoid seeing this error message, always test it by placing the Test Order and going through the full checkout process.
Below are the cases in which this error message will be displayed.
Case 1:
When the Upsell & Downsell pages are opened or viewed directly from the URL and the Flow is not in the Test Mode.
Then on the Upsell & Downsell page, the session key is not set and that is why it displays this error message.
Thus displaying the “Your Session is Expired” message only when you are not logged in.
Case 2:
If the Upsell & Downsell pages are placed after the optin step.
This will not work because on the Optin page there is no Payment Gateway option present and thus it is not possible to accept the payment gateway on the Upsell page. This gives the “Your Session is Expired” error message.
If you want to view the Upsell & Downsell pages just to check the design then you need to set the flow to Test Mode and open the page while you are logged in. This will allow you to view the designs of the Upsell & Downsell pages.
Case 3:
If the cookies are restricted from the Server/hosting.
If you are using any hosting and that has a specific requirement regarding the cookie names then it is most likely to display the Session Expired error message.
This specific requirement includes the name of the cookie. For example, some hosting says that the cookie name should be started with the prefix as wp_ or woocommerce_ or server-specific pre-fix.
As the Cookie which is set by the CartFlows is not accessible on such server/hosting due to above-mentioned cookie requirements and most likely these server does not allow third-party plugins to set their cookies for some security reasons.
For example: Suppose you are using “Pantheon” hosting/server then it will show you the Session Expired message as this server has a specific requirement regarding the Cookie naming.
Actually, there are a number of plugins that use cookies and not all plugins can change the names of their cookies as per the server’s cookie naming structure.
So to fix this error message, you need to get in touch with the hosting/server provider and ask for a way to exclude the CartFlows cookies from these restrictions. Once the cookie is been excluded then you will not get this error message on the Upsell/Downsell pages.
Case 4:
If the website is not properly configured for the SSL/HTTPS connections.
All of the CartFlows Cookies will work on the HTTPS protocol/connection. So it is necessary that your website should be properly configured for HTTPS i:e the SSL has to be installed.
If the HTTPS/SSL is not installed then the cookie will not be registered and you will get the Session Expired error message.
Few Common Questions (FAQs)
Q. What to do if the getting a session expired error message on the checkout page?
Ans: If you are getting the session expired error message on the Checkout page of the CartFlows, then it means that the CartFlows session cookie ( cartflows_session_ ) or the WooCommerce’s Session cookie is not getting registered on the CartFlows page. Usually, this happens when the CartFlows pages are cached at the server end or at the local end. To fix this, you need to clear the cache and exclude the CartFlows Checkout pages from the server-side or local cache.
Related docs –
- List of CartFlows Cookies.
- How to Resolve “Order Does not Exist Error” on Upsell & Downsell Page?
Добрый день. Я с php ничего общего не имею. Немного html баловался в молодости, кое какие принципы и php знаю.Что позволяет мне хоть немного без страха лезть в файловый менеджер и что либо править.
Собственно корпоративный сайт работал долгое время без сбоев и тут вышли распространенная ошибки:
Кодировка у сайта полностью сбилась — крокозябры какие-то. Но это быстро решилось сменой кодировки в панели управления хостинга.
А вот эти ошибки так и остались, с ними в админку не пускает.
Что я сделал? как советовали в интернете — первое, что необходимо сделать это проверить кодировки указанных в ошибке файлов и поставить UTF без BOM. Сказано — сделано, полностью перезалил новый файлы. Ошибка не ушла.
Еще советуют поставить session_start() в самое начало, но что-то при данных попытках сайт у меня вообще ложился)
Собственно код session.php
* @package Joomla.Platform
* @copyright Copyright (C) 2005 — 2014 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
* Class for managing HTTP sessions
* Provides access to session-state values as well as session-level
* settings and lifetime management methods.
* Based on the standard PHP session handling mechanism it provides
* more advanced features such as expire timeouts.
* @package Joomla.Platform
class JSession implements IteratorAggregate
* One of ‘inactive’|’active’|’expired’|’destroyed’|’error’
* @see JSession::getState()
protected $_state = ‘inactive’;
* Maximum age of unused session in minutes
* The session store object.
protected $_store = null;
* List of checks that will be done.
protected $_security = array(‘fix_browser’);
* Force cookies to be SSL only
protected $_force_ssl = false;
* JSession instances container.
protected static $instance;
* The type of storage for the session.
* Holds the JInput object
* Holds the event dispatcher object
private $_dispatcher = null;
* @param string $store The type of storage for the session.
* @param array $options Optional parameters
public function __construct($store = ‘none’, array $options = array())
// Need to destroy any existing sessions started with session.auto_start
// Disable transparent sid support
ini_set(‘session.use_trans_sid’, ‘0’);
// Only allow the session ID to come from cookies and nothing else.
ini_set(‘session.use_only_cookies’, ‘1’);
$this->_store = JSessionStorage::getInstance($store, $options);
$this->storeName = $store;
$this->_setOptions($options);
$this->_setCookieParams();
$this->_state = ‘inactive’;
* Magic method to get read-only access to properties.
* @param string $name Name of property to retrieve
* @return mixed The value of the property
public function __get($name)
if ($name === ‘storeName’)
if ($name === ‘state’ || $name === ‘expire’)
* Returns the global Session object, only creating it
* if it doesn’t already exist.
* @param string $handler The type of session handler.
* @param array $options An array of configuration options.
* @return JSession The Session object.
public static function getInstance($handler, $options)
self::$instance = new JSession($handler, $options);
* Get current state of session
* @return string The session state
public function getState()
* Get expiration time in minutes
* @return integer The session expiration time in minutes
public function getExpire()
* Get a session token, if a token isn’t set yet one will be generated.
* Tokens are used to secure forms from spamming attacks. Once a token
* has been generated the system will check the post request to see if
* it is present, if not it will invalidate the session.
* @param boolean $forceNew If true, force a new token to be created
* @return string The session token
public function getToken($forceNew = false)
$token = $this->get(‘session.token’);
if ($token === null || $forceNew)
$token = $this->_createToken(12);
$this->set(‘session.token’, $token);
* Method to determine if a token exists in the session. If not the
* session will be set to expired
* @param string $tCheck Hashed token to be verified
* @param boolean $forceExpire If true, expires the session
public function hasToken($tCheck, $forceExpire = true)
// Check if a token exists in the session
$tStored = $this->get(‘session.token’);
if (($tStored !== $tCheck))
$this->_state = ‘expired’;
* Method to determine a hash for anti-spoofing variable names
* @param boolean $forceNew If true, force a new token to be created
* @return string Hashed var name
public static function getFormToken($forceNew = false)
$user = JFactory::getUser();
$session = JFactory::getSession();
// TODO: Decouple from legacy JApplication class.
$hash = JApplication::getHash($user->get(‘id’, 0) . $session->getToken($forceNew));
$hash = md5(JFactory::getApplication()->get(‘secret’) . $user->get(‘id’, 0) . $session->getToken($forceNew));
* Retrieve an external iterator.
* @return ArrayIterator Return an ArrayIterator of $_SESSION.
public function getIterator()
return new ArrayIterator($_SESSION);
* Checks for a form token in the request.
* Use in conjunction with JHtml::_(‘form.token’) or JSession::getFormToken.
* @param string $method The request method in which to look for the token key.
* @return boolean True if found and valid, false otherwise.
public static function checkToken($method = ‘post’)
$token = self::getFormToken();
$app = JFactory::getApplication();
if (!$app->input->$method->get($token, », ‘alnum’))
$session = JFactory::getSession();
// Redirect to login screen.
$app->enqueueMessage(JText::_(‘JLIB_ENVIRONMENT_SESSION_EXPIRED’), ‘warning’);
$app->redirect(JRoute::_(‘index.php’));
* @return string The session name
public function getName()
if ($this->_state === ‘destroyed’)
* @return string The session name
if ($this->_state === ‘destroyed’)
* Get the session handlers
* @return array An array of available session handlers
public static function getStores()
// Get an iterator and loop trough the driver classes.
$iterator = new DirectoryIterator(__DIR__ . ‘/storage’);
/* @type $file DirectoryIterator */
foreach ($iterator as $file)
$fileName = $file->getFilename();
// Only load for php files.
if (!$file->isFile() || $file->getExtension() != ‘php’)
// Derive the class name from the type.
// If the class doesn’t exist we have nothing left to do but look at the next type. We did our best.
// Sweet! Our class exists, so now we just need to know if it passes its test method.
if ($class::isSupported())
// Connector names should not have file extensions.
* Shorthand to check if the session is active
public function isActive()
return (bool) ($this->_state == ‘active’);
* Check whether this session is currently created
* @return boolean True on success.
$counter = $this->get(‘session.counter’);
return (bool) ($counter === 1);
* Check whether this session is currently created
* @param JInput $input JInput object for the session to use.
* @param JEventDispatcher $dispatcher Dispatcher object for the session to use.
public function initialise(JInput $input, JEventDispatcher $dispatcher = null)
$this->_dispatcher = $dispatcher;
* Get data from the session store
* @param string $name Name of a variable
* @param mixed $default Default value of a variable if not set
* @param string $namespace Namespace to use, default to ‘default’
* @return mixed Value of a variable
public function get($name, $default = null, $namespace = ‘default’)
// Add prefix to namespace to avoid collisions
$namespace = ‘__’ . $namespace;
if ($this->_state === ‘destroyed’)
// @TODO :: generated error here
if (isset($_SESSION[$namespace][$name]))
return $_SESSION[$namespace][$name];
* Set data into the session store.
* @param string $name Name of a variable.
* @param mixed $value Value of a variable.
* @param string $namespace Namespace to use, default to ‘default’.
* @return mixed Old value of a variable.
public function set($name, $value = null, $namespace = ‘default’)
// Add prefix to namespace to avoid collisions
$namespace = ‘__’ . $namespace;
if ($this->_state !== ‘active’)
// @TODO :: generated error here
$old = isset($_SESSION[$namespace][$name]) ? $_SESSION[$namespace][$name] : null;
unset($_SESSION[$namespace][$name]);
$_SESSION[$namespace][$name] = $value;
* Check whether data exists in the session store
* @param string $name Name of variable
* @param string $namespace Namespace to use, default to ‘default’
* @return boolean True if the variable exists
public function has($name, $namespace = ‘default’)
// Add prefix to namespace to avoid collisions.
$namespace = ‘__’ . $namespace;
if ($this->_state !== ‘active’)
// @TODO :: generated error here
return isset($_SESSION[$namespace][$name]);
* Unset data from the session store
* @param string $name Name of variable
* @param string $namespace Namespace to use, default to ‘default’
* @return mixed The value from session or NULL if not set
public function clear($name, $namespace = ‘default’)
// Add prefix to namespace to avoid collisions
$namespace = ‘__’ . $namespace;
if ($this->_state !== ‘active’)
// @TODO :: generated error here
if (isset($_SESSION[$namespace][$name]))
$value = $_SESSION[$namespace][$name];
unset($_SESSION[$namespace][$name]);
if ($this->_state === ‘active’)
$this->_state = ‘active’;
// Initialise the session
// Perform security checks
if ($this->_dispatcher instanceof JEventDispatcher)
$this->_dispatcher->trigger(‘onAfterSessionStart’);
* Creates a session (or resumes the current one based on the state of the session)
* @return boolean true on success
protected function _start()
// Start session if not started
if ($this->_state === ‘restart’)
// Get the JInputCookie object
$cookie = $this->_input->cookie;
if (is_null($cookie->get($session_name)))
$session_clean = $this->_input->get($session_name, false, ‘string’);
$cookie->set($session_name, », time() — 3600);
* Write and Close handlers are called after destructing objects since PHP 5.0.5.
* Thus destructors can use sessions but session handler can’t use objects.
* So we are moving session closure before destructing objects.
* Replace with session_register_shutdown() when dropping compatibility with PHP 5.3
* Frees all session variables and destroys all data registered to a session
* This method resets the $_SESSION variable and destroys all of the data associated
* with the current session in its storage (file or DB). It forces new session to be
* started after this method is called. It does not unset the session cookie.
* @return boolean True on success
public function destroy()
// Session was already destroyed
if ($this->_state === ‘destroyed’)
* In order to kill the session altogether, such as to log the user out, the session id
* must also be unset. If a cookie is used to propagate the session id (default behavior),
* then the session cookie must be deleted.
$config = JFactory::getConfig();
$cookie_domain = $config->get(‘cookie_domain’, »);
$cookie_path = $config->get(‘cookie_path’, ‘/’);
$this->_state = ‘destroyed’;
* Restart an expired or locked session.
* @return boolean True on success
* @see JSession::destroy()
public function restart()
if ($this->_state !== ‘destroyed’)
// @TODO :: generated error here
// Re-register the session handler after a session has been destroyed, to avoid PHP bug
$this->_store->register();
$this->_state = ‘restart’;
$this->_state = ‘active’;
* Create a new session and copy variables from the old one
* @return boolean $result true on success
if ($this->_state !== ‘active’)
// @TODO :: generated error here
// Re-register the session store after a session has been destroyed, to avoid PHP bug
$this->_store->register();
// Restart session with new id
* Writes session data and ends session
* Session data is usually stored after your script terminated without the need
* to call JSession::close(), but as session data is locked to prevent concurrent
* writes only one script may operate on a session at any time. When using
* framesets together with sessions you will experience the frames loading one
* by one due to this locking. You can reduce the time needed to load all the
* frames by ending the session as soon as all changes to session variables are
* @see session_write_close()
* Set session cookie parameters
protected function _setCookieParams()
$cookie[‘secure’] = true;
$config = JFactory::getConfig();
if ($config->get(‘cookie_domain’, ») != »)
$cookie[‘domain’] = $config->get(‘cookie_domain’);
if ($config->get(‘cookie_path’, ») != »)
$cookie[‘path’] = $config->get(‘cookie_path’);
* @param integer $length Length of string
* @return string Generated token
protected function _createToken($length = 32)
static $chars = ‘0123456789abcdef’;
for ($i = 0; $i < $length; ++$i)
$token .= $chars[(rand(0, $max))];
return md5($token . $name);
* Set counter of session usage
* @return boolean True on success
protected function _setCounter()
$counter = $this->get(‘session.counter’, 0);
$this->set(‘session.counter’, $counter);
* @return boolean True on success
protected function _setTimers()
if (!$this->has(‘session.timer.start’))
$this->set(‘session.timer.start’, $start);
$this->set(‘session.timer.last’, $start);
$this->set(‘session.timer.now’, $start);
$this->set(‘session.timer.last’, $this->get(‘session.timer.now’));
$this->set(‘session.timer.now’, time());
* Set additional session options
* @param array $options List of parameter
* @return boolean True on success
protected function _setOptions(array $options)
if (isset($options[‘name’]))
if (isset($options[‘id’]))
if (isset($options[‘expire’]))
$this->_expire = $options[‘expire’];
if (isset($options[‘security’]))
$this->_security = explode(‘,’, $options[‘security’]);
if (isset($options[‘force_ssl’]))
$this->_force_ssl = (bool) $options[‘force_ssl’];
// Sync the session maxlifetime
ini_set(‘session.gc_maxlifetime’, $this->_expire);
* Do some checks for security reason
* — timeout check (expire)
* If one check failed, session data has to be cleaned.
* @param boolean $restart Reactivate session
* @return boolean True on success
* @see http://shiflett.org/articles/the-truth-about-sessions
protected function _validate($restart = false)
// Allow to restart a session
$this->_state = ‘active’;
$this->set(‘session.client.address’, null);
$this->set(‘session.client.forwarded’, null);
$this->set(‘session.client.browser’, null);
$this->set(‘session.token’, null);
// Check if session has expired
$curTime = $this->get(‘session.timer.now’, 0);
$maxTime = $this->get(‘session.timer.last’, 0) + $this->_expire;
// Empty session variables
$this->_state = ‘expired’;
// Record proxy forwarded for in the session in case we need it later
if (isset($_SERVER[‘HTTP_X_FORWARDED_FOR’]))
$this->set(‘session.client.forwarded’, $_SERVER[‘HTTP_X_FORWARDED_FOR’]);
// Check for client address
if (in_array(‘fix_adress’, $this->_security) && isset($_SERVER[‘REMOTE_ADDR’]))
$ip = $this->get(‘session.client.address’);
$this->set(‘session.client.address’, $_SERVER[‘REMOTE_ADDR’]);
elseif ($_SERVER[‘REMOTE_ADDR’] !== $ip)
// Check for clients browser
if (in_array(‘fix_browser’, $this->_security) && isset($_SERVER[‘HTTP_USER_AGENT’]))
$browser = $this->get(‘session.client.browser’);
$this->set(‘session.client.browser’, $_SERVER[‘HTTP_USER_AGENT’]);
elseif ($_SERVER[‘HTTP_USER_AGENT’] !== $browser)
// @todo remove code: $this->_state = ‘error’;
// @todo remove code: return false;
кто что может подсказать?
Подсказка от модератора:
Любой код или текст конфигурации пишите между тегом [code=php] и [/code].
Используйте отступы в коде для форматирования текста.
Это помогает быстрее понять вас, увеличивает шанс на получение ответа.
Что выделять? Например: PHP, HTML, CSS, JavaScript, SQL, XML, .htaccess, ini, регулярные выражения, код шаблонизаторов, любая другая разметка, результаты array/object dump и т. д.
i’m trying to make a request to a search_read endpoint and the result is session expired, my code is this:
first i login to get the session_id
$data = array(
'json-rpc' => 2.0,
'method' => 'call',
'params' => array(
'db' => 'xxxx',
'login' => 'xxxx',
'password' => 'xxxx',
'context' => array()
),
'id' => 10
);
$data_string = json_encode($data);
$ch = curl_init('https://xxxxxxxxxxxxx/web/session/authenticate');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
)
);
$res = curl_exec($ch);
print_r(json_decode($res)->result->session_id);
response:
{"result": {"uid": 2, "partner_display_name": "ARISMEL", "username": "admin", "odoobot_initialized": true, "web.base.url": "http://xxxxxxxxxxxxxx.com.co", "user_companies": false, "max_time_between_keys_in_ms": 55, "show_effect": "True", "is_system": true, "server_version_info": [12, 0, 0, "final", 0, ""], "is_admin": true, "server_version": "12.0-20210728", "db": "lujosec", "user_context": {"uid": 2, "lang": "es_CO", "tz": "America/Bogota"}, "web_tours": [], "name": "ARISMEL", "partner_id": 3, "session_id": "d48914eb50a0bd286873a88fa660a9459008ee75", "company_id": 1, "currencies": {"8": {"position": "before", "symbol": "$", "digits": [69, 2]}, "1": {"position": "after", "symbol": "u20ac", "digits": [69, 2]}, "2": {"position": "before", "symbol": "$", "digits": [69, 2]}}}, "jsonrpc": "2.0", "id": 10}
Then use the id_session in the header for the other request
$data = array(
'json-rpc' => 2.0,
'method' => 'call',
'params' => array(
'model' => 'res.users',
'fields' => ["id", "name", "login"],
'domain' => array(),
'context' => array(),
),
'id' => 10,
);
$data_string = json_encode($data);
$ch = curl_init('https://xxxxxxxxxxxxxxxxxxxxx/web/dataset/search_read');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'x-openerp-session_id : ' . json_decode($res)->result->session_id,
'Cookie: sessionid='. json_decode($res)->result->session_id ,
)
);
$res = curl_exec($ch);
print_r($res);
response:
{"jsonrpc": "2.0", "error": {"message": "Odoo Session Expired", "data": {"arguments": ["Session expired"], "exception_type": "internal_error", "message": "Session expired", "debug": "Traceback (most recent call last):n File "/usr/lib/python3/dist-packages/odoo/http.py", line 656, in _handle_exceptionn return super(JsonRequest, self)._handle_exception(exception)n File "/usr/lib/python3/dist-packages/odoo/http.py", line 314, in _handle_exceptionn raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])n File "/usr/lib/python3/dist-packages/odoo/tools/pycompat.py", line 87, in reraisen raise valuen File "/usr/lib/python3/dist-packages/odoo/addons/http_routing/models/ir_http.py", line 352, in _dispatchn cls._authenticate(func.routing['auth'])n File "/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_http.py", line 118, in _authenticaten getattr(cls, "_auth_method_%s" % auth_method)()n File "/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_http.py", line 91, in _auth_method_usern raise http.SessionExpiredException("Session expired")nodoo.http.SessionExpiredException: Session expiredn", "name": "odoo.http.SessionExpiredException"}, "code": 100}, "id": 10}
A curious fact is that in postman it works fine, it works without session id I don’t understand it.
Odoo version 12. I was trying in javascript, using responses with fetch or axios but the result is the same,
please help, best regards
Updated: 04/30/2020 by
When browsing a website that is database driven, requires a login, or is secured, you may see a «Session Expired» or «Session Has Expired» error. The most common causes of these error messages are detailed below.
Inactivity
If you have not been doing anything on the page for a set length of time (often 10-30 minutes), the server times out your session. Inactivity timers were created for security reasons and to help increase the overall speed of the web page. For example, if you were browsing the page and got up to leave, you’d need to log in again and create a new session when you returned.
Can I increase the length of time a session expires?
A website session duration is measured and managed on the server, not on your computer. Therefore, you cannot modify the remaining time of a web session.
Unstable Internet connection or disconnects
If your Internet connection is unstable, periodically disconnecting and reconnecting, it can cause a website session to expire. When the Internet connection is lost the website connection can be terminated, resulting in a session expired message if you try to access any page after the Internet reconnects.
- Why is the Internet continuously connecting and disconnecting?
Date or time not correct
Make sure the date and time are properly set on your computer. An incorrect date or time on your computer can cause reconciliation issues between the website and your computer, and can cause the session to expire.
- How to set or change a computer’s date and time.
Cookies
If you’re browsing anonymously or your Internet browser does not have cookies enabled, it causes many sessions to fail. Make sure Internet cookies are enabled in your browser.
- How to enable, disable, view, or delete Internet cookies.
Firewall or proxy
If you’re connecting to the Internet behind a firewall or through a proxy, that might restrict or prohibit the session from being established. If a session is not established, you can get a session expired message immediately or very shortly after connecting to or logging in to a website.
Virus or malware
If your computer is infected with a virus or malware, it can cause problems with establishing or keeping an active session on a website. Make sure you have an antivirus program installed, fully updated, and run a scan to remove any viruses or malware found on the computer.
- How to update an antivirus program.
- How to scan or check for computer viruses.
Other site related issue
If the issue only occurs on a certain site and no other website. Contact the company or webmaster to verify the problem is not on their end.
This topic explains what causes the “Your session has expired” error and how to resolve it.
Use the chart below to determine the possible reason for the error in your application.
- The document’s state is stored on another server
- The CloseDocument or CloseAllDocuments method is called
- The dispose timeout for hibernated documents expired
- Idle timeout for an application pool expired
- Application pool is recycled
- Other reasons
The document’s state is stored on another server
This problem occurs when you use RichEdit or Spreadsheet in a stateless environment (Cloud, Web Farm, Web Garden) without a custom state provider.
A server loads a document to RAM and then opens the document when it receives a request. If additional requests are sent to another server that does not contain the document’s state in its RAM, the “Your session has expired” error occurs.
Solutions
Use a custom state provider
A document state provider allows you to store an opened document’s state in external storage. Web servers check out the requested documents from storage, process them, and return the latest document states. Web servers do not store server-specific states between requests.
We published two ready-to-use state providers for Redis and SQL data stores. You can find source code for these providers (with sample applications) in the following GitHub example:
View Example: aspnet-office-solutions
Use session affinity mode
In session affinity mode, a document’s state is stored in the RAM of the server where the document is opened. All document requests are redirected to this server.
To see an example, refer to the following GitHub solution:
View Example: Azure-SessionAffinity-Starter
You can also use this approach with a different cloud platform.
See the following DevExpress ASP.NET team blog post for more information: Scalability of ASP.NET Office Controls — Azure, Web Gardens, Farms, & Cloud Support.
The CloseDocument or CloseAllDocuments method is called
If multiple users work on a document, the “Your session has expired” error can occur when a user’s actions call the CloseAllDocuments() method or if the CloseDocument(String) method is called with the wrong parameter value.
Solution
- Do not call the CloseAllDocuments() method in a multi-user environment.
- Pass the correct document ID to the CloseDocument(String) method, so that the user only closes his/her copy of the document.
The dispose timeout for hibernated documents expired
When document hibernation is enabled (EnableHibernation), the DocumentManager hibernates inactive open documents after an idle timeout (HibernateTimeout) period has passed. The HibernatedDocumentsDisposeTimeout property specifies how long hibernated documents are stored on the server before disposal. If a user attempts to access a disposed document, the “Your session has expired” error occurs.
Solution
Increase the value of the HibernatedDocumentsDisposeTimeout property. (The default value is 24 hours.)
Idle timeout for an application pool expired
In a stateful environment, a worker process shuts down when the idle timeout period for an application pool expires.
Solution
Increase the Idle Time-out value (20 minutes by default) or set the Idle Time-out to 0 (zero) to disable the timeout.
Application pool is recycled
IIS restarts worker processes that handle requests for application pools.
Solution
Check the application pool recycle settings and increase the Regular Time Interval value.
Other reasons
If none of the above solutions help, contact our Support Center and provide a sample project, a test document, and a video that shows the steps to reproduce this message.
According to connects documentation the session should expire when the browser is closed:
By default
cookie.maxAge
isnull
, meaning no «expires» parameter is set
so the cookie becomes a browser-session cookie. When the user closes the
browser the cookie (and session) will be removed.
I am using express 3 with connect-mysql for session store (Tried with connect-mongo too and its the same), and this is how i set the session data.
req.session.userid = results[0].id;
req.session.ip = req.connection.remoteAddress;
req.session.useragent = req.headers['user-agent'];
req.session.is_logged_in = true;
This all works fine except in google chrome browser for some reason (This is in OS X Lion.I have no possibility to test under win or linux right now).
Anyone had this problem in google chrome and know a way to fix it?
josh3736
138k33 gold badges215 silver badges263 bronze badges
asked Jun 9, 2012 at 1:58
georgesampergeorgesamper
4,9395 gold badges39 silver badges59 bronze badges
This is a fairly wild guess, but I wouldn’t be too surprised if it’s this. Google chrome will keep running in the background if you have any extensions that make use of this installed. If that’s the case after a log off-log in the session should be reset.
If that isn’t it, could you please open the developer tools (cmd+alt+i
) and copy all the information about the cookie from there (resources
->cookies
->yourdomain.com
). (Especially what’s written in the Expires
column, because it should say Session
)
answered Jun 13, 2012 at 19:53
David MulderDavid Mulder
25.9k8 gold badges49 silver badges113 bronze badges
3