I user opencart v2.3.0.2 and after finished my site I use a scanner to scan my website but after while I get this error :
Fatal error: session_set_save_handler(): Session handler's function
table is corrupt in \system\library\session.php on line 16
I have try to add this in my php.ini
session.save_path = "/temp";
but I still get the same error. I use XAMPP.
the session file :
<?php
class Session {
public $session_id = '';
public $data = array();
public function __construct($adaptor = 'native') {
$class = 'Session\\' . $adaptor;
if (class_exists($class)) {
$this->adaptor = new $class($this);
} else {
throw new \Exception('Error: Could not load session adaptor ' . $adaptor . ' session!');
}
if ($this->adaptor) {
session_set_save_handler($this->adaptor);
}
if ($this->adaptor && !session_id()) {
ini_set('session.use_only_cookies', 'Off');
ini_set('session.use_cookies', 'On');
ini_set('session.use_trans_sid', 'Off');
ini_set('session.cookie_httponly', 'On');
if (isset($_COOKIE[session_name()]) && !preg_match('/^[a-zA-Z0-9,\-]{22,52}$/', $_COOKIE[session_name()])) {
exit('Error: Invalid session ID!');
}
session_set_cookie_params(0, '/');
session_start();
}
}
public function start($key = 'default', $value = '') {
if ($value) {
$this->session_id = $value;
} elseif (isset($_COOKIE[$key])) {
$this->session_id = $_COOKIE[$key];
} else {
$this->session_id = $this->createId();
}
if (!isset($_SESSION[$this->session_id])) {
$_SESSION[$this->session_id] = array();
}
$this->data = &$_SESSION[$this->session_id];
if ($key != 'PHPSESSID') {
setcookie($key, $this->session_id, ini_get('session.cookie_lifetime'), ini_get('session.cookie_path'), ini_get('session.cookie_domain'), ini_get('session.cookie_secure'), ini_get('session.cookie_httponly'));
}
return $this->session_id;
}
public function getId() {
return $this->session_id;
}
public function createId() {
if (version_compare(phpversion(), '5.5.4', '>') == true) {
return $this->adaptor->create_sid();
} elseif (function_exists('random_bytes')) {
return substr(bin2hex(random_bytes(26)), 0, 26);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
return substr(bin2hex(openssl_random_pseudo_bytes(26)), 0, 26);
} else {
return substr(bin2hex(mcrypt_create_iv(26, MCRYPT_DEV_URANDOM)), 0, 26);
}
}
public function destroy($key = 'default') {
if (isset($_SESSION[$key])) {
unset($_SESSION[$key]);
}
setcookie($key, '', time() - 42000, ini_get('session.cookie_path'), ini_get('session.cookie_domain'));
}
}
not important section ://
blablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablabla//
Just restart the apache & mysql. It will solve the error.
Related
my script has a problem and gives me this warning:
Warning: session_start(): Failed to read session data: user (path:
/Users/soroush/Documents/www/new/tmp/session) in
/Users/soroush/Documents/www/new/include/class.session.php on line 35
this is my class:
class SecureSessionHandler extends SessionHandler {
protected $key, $name, $cookie;
public function __construct($name = 'MY_SESSION', $cookie = [])
{
$this->key = SESSION_KEY;
$this->name = $name;
$this->cookie = $cookie;
$this->cookie += [
'lifetime' => 0,
'path' => ini_get('session.cookie_path'),
'domain' => ini_get('session.cookie_domain'),
'secure' => isset($_SERVER['HTTPS']),
'httponly' => true
];
$this->setup();
}
private function setup()
{
ini_set('session.use_cookies', 1);
ini_set('session.use_only_cookies', 1);
session_name($this->name);
session_set_cookie_params(
$this->cookie['lifetime'],
$this->cookie['path'],
$this->cookie['domain'],
$this->cookie['secure'],
$this->cookie['httponly']
);
}
public function start()
{
if (session_id() === '') {
if (session_start()) {
return mt_rand(0, 4) === 0 ? $this->refresh() : true; // 1/5
}
}
return false;
}
public function forget()
{
if (session_id() === '') {
return false;
}
$_SESSION = [];
setcookie(
$this->name,
'',
time() - 42000,
$this->cookie['path'],
$this->cookie['domain'],
$this->cookie['secure'],
$this->cookie['httponly']
);
return session_destroy();
}
public function refresh()
{
return session_regenerate_id(true);
}
public function read($id)
{
$data = openssl_decrypt(parent::read($id),'AES256',$this->key);
return $data;
}
public function write($id, $data)
{
return parent::write($id, openssl_encrypt(parent::read($id),'AES256',$this->key));
}
public function isExpired($ttl = 30)
{
$last = isset($_SESSION['_last_activity'])
? $_SESSION['_last_activity']
: false;
if ($last !== false && time() - $last > $ttl * 60) {
return true;
}
$_SESSION['_last_activity'] = time();
return false;
}
public function isFingerprint()
{
$hash = md5(
$_SERVER['HTTP_USER_AGENT'] .
(ip2long($_SERVER['REMOTE_ADDR']) & ip2long('255.255.0.0'))
);
if (isset($_SESSION['_fingerprint'])) {
return $_SESSION['_fingerprint'] === $hash;
}
$_SESSION['_fingerprint'] = $hash;
return true;
}
public function isValid()
{
return ! $this->isExpired() && $this->isFingerprint();
}
public function get($name)
{
$parsed = explode('.', $name);
$result = $_SESSION;
while ($parsed) {
$next = array_shift($parsed);
if (isset($result[$next])) {
$result = $result[$next];
} else {
return null;
}
}
return $result;
}
public function put($name, $value)
{
$parsed = explode('.', $name);
$session =& $_SESSION;
while (count($parsed) > 1) {
$next = array_shift($parsed);
if ( ! isset($session[$next]) || ! is_array($session[$next])) {
$session[$next] = [];
}
$session =& $session[$next];
}
$session[array_shift($parsed)] = $value;
}
}
and i use this class like this:
$session = new SecureSessionHandler();
ini_set('session.save_handler', 'files');
session_set_save_handler($session, true);
session_save_path(SITE_PATH.'tmp/session');
$session->start();
if ( ! $session->isValid(5)) {
$session->destroy();
die();
}
$session->put('site.langu', $lang->lang);
but it give me a warning in php 7.1
i use a mac os system and do this works
give 0777 permission to session folder
change chown with php running group and user
what should I do to fix this warning?
i solved this problem with this change:
public function read($id)
{
return (string)openssl_decrypt (parent::read($id) , "aes-256-cbc", $this->key);
}
public function write($id, $data)
{
return parent::write($id, openssl_encrypt($data, "aes-256-cbc", $this->key));
}
viva google :))
I am creating my own custom cookie class and I can not seem to figure out what I am doing wrong. Here is my cookie class:
<?php
class Cookie implements CookieHandlerInterface {
private $_domain;
private $_secure;
public function __construct(array $config = array()) {
$this->_domain = isset($config['domain']) ? $config['domain'] : 'localhost';
$this->_secure = isset($config['secure']) ? $config['secure'] : false;
}
public function set($name, $value = null, $timeLength) {
if (!is_null($value)) {
if (is_array($value)) {
if ($this->__isMultiArray($array)) {
return null;
} else {
$value = $this->__arrayBuild($value);
$value = 'array(' . $value . ')';
}
} elseif (is_bool($value)) {
if ($value) {
$value = 'bool(true)';
} else {
$value = 'bool(false)';
}
} elseif (is_int($value)) {
$value = 'int(' . strval($value) . ')';
} elseif (is_float($value)) {
$value = 'float(' . strval($value) . ')';
} elseif (is_string($value)) {
$value = 'string(' . $value . ')';
} else {
return null;
}
} else {
$value = 'null(null)';
}
setcookie($name, $value, (time() + $timeLength), '/', $this->_domain, $this->_secure, true);
}
public function get($name, $defualtOutput = null) {
if (isset($_COOKIE[$name])) {
$output = rtrim($_COOKIE[$name], ')');
$xr1 = mb_substr($output, 0, 1);
if (equals($xr1, 'a')) {
$output = ltrim($output, 'array(');
return $this->__arrayBreak($output);
}
if (equals($xr1, 'b')) {
$output = ltrim($output, 'bool(');
if (equals($output, 'true')) {
return true;
} else {
return false;
}
}
if (equals($xr1, 'i')) {
$output = ltrim($output, 'int(');
return (int) $output;
}
if (equals($xr1, 'f')) {
$output = ltrim($output, 'float(');
return (float) $output;
}
if (equals($xr1, 's')) {
$output = ltrim($output, 'string(');
return $output;
}
if (equals($output, 'null(null)')) {
return null;
}
}
if (
!is_array($defualtOutput)
&& !is_bool($defualtOutput)
&& !is_int($defualtOutput)
&& !is_float($defualtOutput)
&& !is_string($defualtOutput)
&& !is_null($defualtOutput)
) {
trigger_error(
'The $defualtOutput var needs to be only certain types of var types. Allowed (array, bool, int, float, string, null).',
E_USER_ERROR
);
}
return $defualtOutput;
}
public function delete($name) {
if (isset($_COOKIE[$name])) {
setcookie($name, '', time() - 3600, '/', $this->_domain, $this->_secure, true);
}
}
private function __arrayBuild($array) {
$out = '';
foreach ($array as $index => $data) {
$out .= ($data != '') ? $index . '=' . $data . '|' : '';
}
return rtrim($out, '|');
}
private function __arrayBreak($cookieString) {
$array = explode('|', $cookieString);
foreach ($array as $i => $stuff) {
$stuff = explode('=', $stuff);
$array[$stuff[0]] = $stuff[1];
unset($array[$i]);
}
return $array;
}
private function __isMultiArray($array) {
foreach ($array as $key => $value) {
if (is_array($value)) {
return true;
}
}
return false;
}
}
?>
I set a test cookie for example app('cookie')->set('test', 'hello', 0);
sure enough it created the cookie like expected. So the cookie reads string(hello)
When I try to echo it, it echos the default value instead of the actual variable, so app('cookie')->get('test', 'test'); returns test
The get function should check if the cookie exists with isset($_COOKIE[$cookieName]) and then it should trim the extra ) with rtrim($_COOKIE[$cookieName], ')') then it should grab the first character in the string with mb_substr($_COOKIE[$cookieName], 0, 1) the 0 starts at the beginning and the 1 grabs only the first character.
After it compares it with the default (a, b, i, f, s) for example if it starts with an s its a string by default, if it was i it was sent as an int by default, etc. etc.
If they all come up as false it checks to see if it was sent as null if so it return null else it returns the default value passed.
The equals function is the same as $var1 == $var2 it is timing attack safe.
so it keeps returning the default value which is null, any help would be helpful thanks in advance.
Lol i feel real stupid i put 0 as the third argument thinking it will tell the cookie to expire when the browser session closes, but it did (time() + 0) which does not equal 0. so as it was setting the cookie it expired upon creation. So i did time() - (time() * 2). i achieved the goal i wanted.
I am currently setting up a website using Opencart. When registering an account on the website I obtain the following:
Warning: Invalid argument supplied for foreach() in
/homepages/2/d493065440/htdocs/sofas/system/library/mail.php on line
22Warning: Cannot modify header information - headers already sent by
(output started at /homepages/2/d493065440/htdocs/sofas/index.php:98)
in /homepages/2/d493065440/htdocs/sofas/system/library/response.php on
line 12
Does anyone know how to avoid this message? The weird thing is the account is still created? I have attached the response.php file. Any help would be much appreciated!
<?php
class Response {
private $headers = array();
private $level = 0;
private $output;
public function addHeader($header) {
$this->headers[] = $header;
}
public function redirect($url, $status = 302) {
header('Location: ' . str_replace(array('&', "\n", "\r"), array('&', '', ''), $url), true, $status);
exit();
}
public function setCompression($level) {
$this->level = $level;
}
public function setOutput($output) {
$this->output = $output;
}
public function getOutput() {
return $this->output;
}
private function compress($data, $level = 0) {
if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false)) {
$encoding = 'gzip';
}
if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false)) {
$encoding = 'x-gzip';
}
if (!isset($encoding) || ($level < -1 || $level > 9)) {
return $data;
}
if (!extension_loaded('zlib') || ini_get('zlib.output_compression')) {
return $data;
}
if (headers_sent()) {
return $data;
}
if (connection_status()) {
return $data;
}
$this->addHeader('Content-Encoding: ' . $encoding);
return gzencode($data, (int)$level);
}
public function output() {
if ($this->output) {
if ($this->level) {
$output = $this->compress($this->output, $this->level);
} else {
$output = $this->output;
}
if (!headers_sent()) {
foreach ($this->headers as $header) {
header($header, true);
}
}
echo $output;
}
}
}
This question already has answers here:
PHP - unexpected end of file
(3 answers)
Closed 8 years ago.
I am getting an unexpected end of file error on the last line of this code, I have run it through www.phpcodechecker.com (Which I have found do be very reliable). What am I doing wrong? PHP version 5.5.9
<?php
/*
Hurricane Control Panel © 2014, a web control panel
by Hurricane Development of http://www.HurricaneDevelopment.com
is licenced under a Creative Commons
Attribution-NoDerivatives 4.0 International License
Permissions beyond the scope of this licence
may be available at http://creativecommons.org/licenses/by-nd/4.0/
*/
Defined("_HEXEC") or die ("This file may not be accessed directly");
class VARS {
public static $errors = false;
public static $extraJS = false;
public static $scriptJS = false;
public static $extraCSS = false;
}
abstract class GeneralUTIL {
/**
* Error functions
**/
public static function addErr($err) {
VARS::$errors[] = $err;
}
public static function logger($content,$level = LOGGER_INFO) {
if (!file_exists("logs")) {
mkdir("logs");
}
$scanned_directory = array_diff(scandir("logs",SCANDIR_SORT_DESCENDING), array('..', '.'));
$logs = false;
if (sizeof($scanned_directory) == 0) {
file_put_contents("logs/log.1", "", LOCK_EX);
chmod("logs/log.1",0600);
$logid = 1;
} else {
foreach ($scanned_directory as $key => $value) {
if (strpos($value,"log.") !== false) {
$logs[] = $value;
}
}
$logid = explode(".", $logs[0]);
$logid = $logid[1];
if (filesize("logs/log." . $logid) >= 200000) {
$logid = ((int) $logid) + 1;
file_put_contents("logs/log." . $logid, "", LOCK_EX);
chmod("logs/log." . $logid,0600);
}
}
date_default_timezone_set("America/New_York");
$d = getdate();
file_put_contents("logs/log." . $logid, "{$d['mon']}/{$d['mday']}/{$d['year']} {$d['hours']}:{$d['minutes']}:{$d['seconds']} $level $content \n", FILE_APPEND | LOCK_EX);
}
public static function sha512($password,$salt = null) {
if ($salt == null) {
$cost = 50000;
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
$salt = sprintf('$6$rounds=%d$', $cost) . $salt;
}
return crypt($password, $salt);
}
public static function matchSha512($password,$hash) {
if (crypt($password, $hash) === $hash) {
return true;
}
return false;
}
}
class PluginUTIL extends GeneralUTIL {
public static function addJS($jsPath) {
$debugArray = debug_backtrace();
$pluginAlias = UTIL::getBetween($debugArray[0]['file'],"/plugins/plugin_","/");
if ($pluginAlias == false) {
UTIL::addErr("The addJS Method was not called from a registered plugin");
return false;
}
$pluginLoader = new Plugins();
$pluginLoader->loadPlugins();
$plugins = $pluginLoader->getPluginsArray();
foreach ($plugins as $id => $pluginArray) {
if ($pluginArray['alias'] == $pluginAlias) {
VARS::$extraJS[] = PATH . "plugins/plugin_" . $pluginAlias . "/" . $jsPath;
return true;
}
}
}
public static function addScriptJS($script) {
VARS::$scriptJS = $script;
}
public static function addCSS($cssPath) {
$debugArray = debug_backtrace();
$pluginAlias = UTIL::getBetween($debugArray[0]['file'],"/plugins/plugin_","/");
if ($pluginAlias == false) {
UTIL::addErr("The addCSS Method was not called from a registered plugin");
return false;
}
$pluginLoader = new Plugins();
$pluginLoader->loadPlugins();
$plugins = $pluginLoader->getPluginsArray();
foreach ($plugins as $id => $pluginArray) {
if ($pluginArray['alias'] == $pluginAlias) {
VARS::$extraCSS[] = PATH . "plugins/plugin_" . $pluginAlias . "/" . $cssPath;
return true;
}
}
}
}
class UTIL extends GeneralUTIL {
public static function displayErrors($output) {
if (VARS::$errors != false && is_array(VARS::$errors)) {
$output = str_replace("<div id='errors' class='alert alert-danger'></div>","<div id='errors' class='alert alert-danger'><h1>Uh Oh. Some errors occured!</h1>" . implode("<br>",VARS::$errors) . "</div>",$output);
} else {
$output = str_replace("<div id='errors' class='alert alert-danger'></div>","",$output);
}
return $output;
}
/**
* Custom JS /CSS functions
**/
public static function addCustomJSFromPath($path) {
VARS::$extraJS[] = PATH . $path;
}
public static function includeCustomJS() {
if (VARS::$extraJS != false && is_array(VARS::$extraJS)) {
foreach (VARS::$extraJS as $key => $path): ?>
<script src="<?php echo $path; ?>"></script>
<?php endforeach;
}
if (VARS::$scriptJS != false): ?>
<script type="text/javascript">
<?php echo VARS::$scriptJS; ?>
</script>
<? endif;
}
public static function includeCustomCSS($output) {
if (VARS::$extraCSS != false && is_array(VARS::$extraCSS)) {
$css = "";
foreach (VARS::$extraCSS as $key => $path):
$css .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"$path\">\n";
endforeach;
$output = str_replace("CUSTOMCSSAREAHERE",$css,$output);
} else {
$output = str_replace("CUSTOMCSSAREAHERE","",$output);
}
return $output;
}
/**
* Get Between two strings function
**/
public static function getBetween($content,$start,$end) {
if (preg_match('/' . str_replace("/","\\/", $start) . '(.*?)' . str_replace("/","\\/", $end) . '/',$content, $res) === false) {
return false;
}
return $res[1];
}
/**
* Redirect page function
**/
public static function redirect($location, $code = '302') {
switch($code) {
case '301';
header("HTTP/1.1 301 Moved Permanently");
break;
case '303';
header("HTTP/1.1 303 See Other");
break;
case '404';
header('HTTP/1.1 404 Not Found');
break;
}
//remove any & in the url to prevent any problems
$location = str_replace('&', '&', $location);
header("Location: $location");
//kill the script from running and output a link for browsers which enable turning off header redirects *cough Opera cough* :P
exit('If you were not redirected automatically please click here');
}
}
?>
Change this
<? endif;
to this
<?php endif;
inside UTIL::includeCustomJS
I am working on a PHP application wherein, i have written a Session Class. However, i am running into a strange issue. Everytime i refresh the page a new session is created.
Also, C:\xampp\tmp is writable (i am on xampp) and session_id() always returns null.
Below is my Session Class
<?php
/**
* Class and Function List:
* Function list:
* - __construct()
* - start()
* - stop()
* - generate_sid()
* - set()
* - delete()
* - get()
* - check()
* - flash()
* Classes list:
* - Session
*/
class Session
{
public $flashElements = array();
public function __construct($autoStart = true)
{
$this->started = isset($_SESSION);
e("The Session Id is " . session_id());
if (!is_writable(session_save_path()))
{
echo 'Session save path "' . session_save_path() . '" is not writable!';
}
e(session_save_path());
if ($this->started && $autoStart === false)
{
$this->start();
}
e("The Session Id is " . session_id());
}
public function start()
{
if (!$this->started)
{
session_id($this->generate_sid());
session_start();
$this->started = true;
}
}
public function stop($clearCookie = true, $clearData = true)
{
if ($this->started)
{
if (($clearCookie) && Configure::get('session.useCookie'))
{
$params = session_get_cookie_params();
setcookie(session_name() , '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
}
if ($clearData)
{
$_SESSION = array();
}
session_destroy();
session_write_close();
$this->started = false;
}
}
public function generate_sid($chars = 100, $alpha = true, $numeric = true, $symbols = true, $timestamp = true)
{
if ($chars < 0 || !is_numeric($chars))
{
return false;
}
$salt = Configure::get('security.salt');
if ($alpha)
{
$salt.= 'abcdefghijklmnopqrstuvwxyz';
}
if ($numeric)
{
$salt.= '1234567890';
}
if ($symbols)
{
$salt.= '-_';
}
$sid = null;
for ($i = 1;$i <= $chars;$i++)
{
$sid.= $saltmt_rand(0, strlen($salt) - 1);
if (mt_rand(0, 1) === 1)
{
$sid
{
strlen($sid) - 1} = strtoupper($sid
{
strlen($sid) - 1});
}
}
if ($timestamp)
{
$sid.= time();
}
return $sid;
}
public function set($keyword, $value)
{
$_SESSION[$keyword] = $value;
}
public function delete($keyword)
{
unset($_SESSION[$keyword]);
$this->flashElements[$keyword] = null;
unset($this->flashElements[$keyword]);
}
public function get($keyword)
{
$returnVar = isset($_SESSION[$keyword]) ? $_SESSION[$keyword] : false;
if (isset($this->flashElements[$keyword]))
{
$this->delete($keyword);
}
return $returnVar;
}
public function check($keyword)
{
return isset($_SESSION[$keyword]) ? true : false;
}
public function flash($value)
{
$this->set('flash', $value);
$this->flashElements['flash'] = $value;
}
}
Please suggest where am i going wrong
I think you're not creating a session because you only call the start function when
$autostart === false
Where it is true by default;
Silly of me. Got it working.
changed the below code in __construct() function
if ($this->started == false && $autoStart != false)
{
$this->start();
}
Thanks Guys!