I tried to program a simple disclaimer plugin for wordpress, which every time a new user access my site shows a disclaimer popup. I've used php session variables but they don't get deleted in chrome when a user restart his browser. I really don't know why it isn't working?
add_filter('init','check_disclaimer');
function check_disclaimer()
{
if (session_status() == PHP_SESSION_NONE)
{
session_set_cookie_params(0);
session_start();
}
if(isset($_POST['disclaimer-accepted']))
{
$_SESSION['disclaimer']=1;
}
if ( !is_user_logged_in() )
{
if (!isset($_SESSION['disclaimer']))
{
include('includes/overlay.php');
}
}
}
Related
I have some code that I added to try and prevent the user from auto logging out (session). - but it still logs the user after so long
What I want is for the user to be able to access multiple pages when logged in and not log them out if they go idle, hence why I put a large idle time - or in other words , stay logged in until they decide to click logout.
login-page
$result = mysqli_query($connection,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
$_SESSION['username']=time();
// Redirect user to index.php
header("Location: admin-index.php");
}else{
$_SESSION['incorrect'] = 'Incorrect email or password. Please try again.';
header ("Location: admin-login.php?=incorrectlogin");
}
}
logged in index page
<?php
session_start();
$idletime=6000000;
if (time()-$_SESSION['username']>$idletime){
session_destroy();
session_unset();
header ("Location: admin-login.php");
}else{
$_SESSION['username']=time();
}
//on session creation
$_SESSION['username']=time();
?>
<!DOCTYPE html>
<html lang="en" >
<head>
second php page
<?php
session_start();
if(!isset($_SESSION["username"])){
header("Location: admin-login.php");
exit(); }
?>
There are a few ways of handling this:
You could change the lifespan of the sessions on the servers itself or if you can't access the server settings, you could try overwriting it through code:
ini_set('session.gc_maxlifetime', 6000000);
session.gc_maxlifetime manual
If you are unable to change the lifespan of sessions on the server, you could use this small code 'trick', keep in minde that if the clients pc shuts down or goes into sleep mode, the sessions will also expire:
Basicly you create a php script containing:
session_start();
Second you just write some jquery with the following code:
$(document).ready(function() {
// keep alive
setTimeout(keepalive(),120000);
});
function keepalive() {
$.get( "url/to/ajax.php", function( data ) { setTimeout(callserver,12000); });
}
You can use a trick, http://php.net/manual/en/function.session-start.php#example-5997
Starting with Php version 7.0 was added an option to prevent session expire. A time of 86400 means 1 days. You can adjust as you want.
if (session_status() == PHP_SESSION_NONE) {
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
session_start(['cookie_lifetime' => 86400,]);
} else {
session_start();
}
}
You can put at the top of Php files or include a file with this code on your project.
Hope this help.
I am working on a school project where I need my .php pages communicating. I have header.php where I set connection to the database and start the session. In order to start the session only once, I've used this:
if(session_id() == '') {
session_start();
}
PHP version is PHP 5.3.10-1 ubuntu3.18 with Suhosin-Patch (cli)
I am trying to pass some $_SESSION variables between pages, but they keep being unset when I try to use them on a page that doesn't set them.
I see many people have complained about this, but I still can't find the solution.
login-form.php
<?php
if (isset($_SESSION["login-error"])) {
echo '<p>'.$_SESSION["login-error"].'</p>';
}
?>
login.php
$_SESSION["login-error"]= "Username or password incorrect";
There is a code snippet of what is not working for me.
Thanks
You can try this.
In your function file put this
function is_session_started()
{
if ( php_sapi_name() !== 'cli' ) {
if ( version_compare(phpversion(), '5.4.0', '>=') ) {
return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
} else {
return session_id() === '' ? FALSE : TRUE;
}
}
return FALSE;
}
Then you can run this in every page you want session started
if ( is_session_started() === FALSE ) session_start();
With this I think you should be good to go on starting your session across pages. Next is to ensure you set a session to a value. If you are not sure what is unsetting your sessions you can try var_dump($_SESSION) at different parts of your code so you be sure at what point it resets then know how to deal with it.
The variables are probable not set, because you haven't activate the session variables with session_start().
session_id() == '' is not a correct conditional . Use instead:
if (!isset($_SESSION)) { session_start();}
if you have session started then you can set a session variable
if (!isset($_SESSION["login-error"])) { $_SESSION["login-error"]= "Username or password incorrect";}
Before you call $_SESSION["login-error"], type session_start(), just for testing, to find when the session signal is missing. You said
PHP $_SESSION variables are not being passed between pages
session_start() and SESSION variables needs to be included at the beginning of EVERY page or at the place where SESSION variables are being called (through a common file, bootstrap, config or sth) at the beginning of EVERY page. ie the command to read those data from the server is needed.
Since my header.php file included "connection.php" file, I put
session_start();
at the beginning of connection.php and deleted it from header.php file. Now it works fine. Thanks all for your help!
PHP sessions rely on components of HTTP, like Cookies and GET variables, which are clearly not available when you're calling a script via the CLI. You could try faking entries in the PHP superglobals, but that is wholly inadvisable. Instead, implement a basic cache yourself.
<?php
class MyCache implements ArrayAccess {
protected $cacheDir, $cacheKey, $cacheFile, $cache;
public function __construct($cacheDir, $cacheKey) {
if( ! is_dir($cacheDir) ) { throw new Exception('Cache directory does not exist: '.$cacheDir); }
$this->cacheDir = $cacheDir;
$this->cacheKey = $cacheKey;
$this->cacheFile = $this->cacheDir . md5($this->cacheKey) . '.cache';
// get the cache if there already is one
if( file_exists($this->cacheFile) ) {
$this->cache = unserialize(file_get_contents($this->cacheFile));
} else {
$this->cache = [];
}
}
// save the cache when the object is destructed
public function __destruct() {
file_put_contents($this->cacheFile, serialize($this->cache));
}
// ArrayAccess functions
public function offsetExists($offset) { return isset($this->cache[$offset]); }
public function offsetGet($offset) { return $this->cache[$offset]; }
public function offsetSet($offset, $value) { $this->cache[$offset] = $value; }
public function offsetUnset($offset) { unset($this->cache[$offset]); }
}
$username = exec('whoami');
$c = new MyCache('./cache/', $username);
if( isset($c['foo']) ) {
printf("Foo is: %s\n", $c['foo']);
} else {
$c['foo'] = md5(rand());
printf("Set Foo to %s", $c['foo']);
}
Example runs:
# php cache.php
Set Foo to e4be2bd956fd81f3c78b621c2f4bed47
# php cache.php
Foo is: e4be2bd956fd81f3c78b621c2f4bed47
This is pretty much all PHP's sessions do, except a random cache key is generated [aka PHPSESSID] and is set as a cookie, and the cache directory is session.save_path from php.ini.
I am trying to change the session time in my login code, and here is the code I want to change the session time in:
<?php
if(session_id()==='')
{
session_start();
}
if(!(isset($_SESSION['status']) && $_SESSION['status'] == "logged_in"))
{
die("sorry, you must be logged in to view this page");
} else {
?>
How would I go about changing the session time?
Also, if you can't change the session time in this, is there any code that can replace this and still work the same?
You may try session_cache_expire
session_cache_expire(30);
$cache_expire = session_cache_expire();
or see this
Currently I have a very basic PHP login system. My index.php file simply checks if a session is set, if it isn't it redirects them to login.php. I see a lot of websites where the same effect is achieved but through the index of the site entirely.
For example, at http://twitter.com if I am not logged in I will land at simply twitter.com. If I am logged in I will also land at twitter.com just with different content. How can I achieve the same effect on my site?
I'm sure this is very basic but it's something I am yet to explore.
Thanks
A simple example how you can handle your welcome/user index.php site:
index.php
require_once('configFile.php'); // session_start();.. and other stuff
if ($logged) {
require_once('userLogedIn/index.php');
} else {
require_once('welcome/index.php');
}
Lots of ways to do this but the below is a primitive example. Assuming your pseudo logic is something like...
if (!$logged_in) {
redirect('login.php');
}
else {
// show page content
}
You can do...
if (!$logged_in) {
include('login.php');
}
else {
include('page-content.php');
}
The includes aren't necessarily required but help to keep it tidy.
First of all answer yourself the question if your index file can contain user supplied stuff. If so DON'T DO IT! The problem are possible attack vectors from that user supplied stuff against your login.
That said let me help you:
<?php
$session_id = session_id();
if (!empty($_COOKIE[$session_id]) && session_start() !== false && isset($_SESSION["user_id"])) {
echo "index page";
}
elseif (isset($_POST["login"])) {
// validate login ...
if ($valid_login === true) {
if (session_status() === PHP_SESSION_ACTIVE) {
session_regenerate_id();
}
else {
session_start();
}
$_SESSION["user_id"] = $user_id;
}
}
else {
echo "login page";
}
?>
I think you get the idea here. We now have a single file taking care of everything.
I'm creating a bilingual site and have decided to use session_start to determine the language of the page using the following:
session_start();
if(!isset($_SESSION['language'])){
$_SESSION['language'] = 'English'; //default language
}
The problem with this is that it clashes with Wordpress and I get the following:
Warning: session_start() [function.session-start]: Cannot send session
cookie - headers already sent by (output started at
/home/neurosur/public_html/v2/wp-content/themes/default/header.php:8)
in /home/neurosur/public_html/v2/wp-content/themes/default/region.php
on line 13
Is there a way to get around this?
EDIT
Wordpress sends header info before the header.php file is run. So starting the session in the header.php may still conflict with the header info that wordpress sends. Running it on init avoids that problem. (From jammypeach's comment)
Write the following code in your functions.php file:
function register_my_session()
{
if( !session_id() )
{
session_start();
}
}
add_action('init', 'register_my_session');
Now if you want to set data in session, do like this
$_SESSION['username'] = 'rafi';
I've changed my original answer to the correct one from #rafi (see below).
Write the following code in your functions.php file:
function register_my_session()
{
if( !session_id() )
{
session_start();
}
}
add_action('init', 'register_my_session');
I found an interesting article by Peter here. I'm using the following code in my functions.php:
add_action('init', 'myStartSession', 1);
add_action('wp_logout', 'myEndSession');
add_action('wp_login', 'myEndSession');
function myStartSession() {
if(!session_id()) {
session_start();
}
}
function myEndSession() {
session_destroy ();
}
This destroys old session when user logs out then in again with different account.
Based on this answer and the answers given here, it's best to use the following code snippets:
For versions of PHP >= 5.4.0, PHP 7:
function register_my_session() {
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
}
add_action('init', 'register_my_session');
Reference: http://www.php.net/manual/en/function.session-status.php
For versions of PHP < 5.4.0:
function register_my_session() {
if(session_id() == '') {
session_start();
}
}
add_action('init', 'register_my_session');
Reference: https://www.php.net/manual/en/function.session-id.php
I don't want to take any credits, I just felt like sharing this information would be helpful.
for PHP version 7.4
function register_my_session() {
if (session_status() === PHP_SESSION_NONE && session_status() !== PHP_SESSION_ACTIVE) {
#session_start();
}
}
add_action('init', 'register_my_session');
add_action('init', 'customSessionStart', 1);
add_action('wp_logout', 'customSessionDestroy');
add_action('wp_login', 'customSessionDestroy');
function customSessionStart()
{
if (!session_id()) {
session_start();
}
}
function customSessionDestroy()
{
session_destroy();
}
When you use this code, you may get the critical issue in the WP Site Health Status. The error says that;
A PHP session was created by a session_start() function call. This interferes with REST API and loopback requests. The session should be closed by session_write_close() before making any HTTP requests.
To suppress this error, you may make this revision when you want to start a session in the WP;
session_start([
'read_and_close' => true,
]);