Cookie that mysteriously sets itself - php

When the condition of the first if statement is met, the cookie "c2" is also set. I'm really scratching my head here. Any ideas? FYI this is the only code that handles cookies on this page.
<?php
//set cookies on correct answers
if ( $_POST['answer-1'] == 'rob' ) :
$c1 = 'correct';
setcookie('c1', 'correct');
endif;
if ( $_POST['answer-2'] == 'blue' ) :
$c2 = 'correct';
setcookie('c2', 'correct');
endif;
//reset cookies
if ( !empty($_POST['reset']) ) :
$_COOKIE['c1'] = '';
$_COOKIE['c2'] = '';
endif;
$c1c = $_COOKIE['c1'];
$c2c = $_COOKIE['c2'];
?>

This:
//reset cookies
if ( !empty($_POST['reset']) ) :
$_COOKIE['c1'] = '';
$_COOKIE['c2'] = '';
endif;
will reset the global $_COOKIE array with these values. But a page reload will still populate that again, as the cookies are still valid and stored in the browser.
In order to also delete them from the browser, you need:
//reset cookies
if ( !empty($_POST['reset']) ) :
$_COOKIE['c1'] = '';
$_COOKIE['c2'] = '';
setcookie('c1', '', -3600);
setcookie('c2', '', -3600);
endif;

Related

Add more data into cookie in PHP

I have a cookie and I'm storing multiple checked checkbox values of page1 in this. Now I want to add more checked checkbox values into the cookie of page2 and then page3 and so on (I'm using pagination in my code). How can I do that in PHP?
<?php
$cookiename = "emp";
if (isset($_GET['check_list']) ) {
setcookie($cookiename , implode(',' , $_GET['check_list']) ,
time()+(86400/86400*30) );
}
?>
//to print the values
<?php
if (isset($_COOKIE[$cookiename]) ) {
print_r($_COOKIE);
}
?>
Maybe in this way:
<?php
$page = $_GET['page'];
$cookiename = "emp";
// GET COOKIE TO NOT OVERWRITE.
$cookie = isset($_COOKIE[$cookiename]) ? unserialize($_COOKIE[$cookiename]) : [];
if (isset($_GET['check_list']) ) {
$cookie[$page] = $_GET['check_list'];
setcookie($cookiename , serialize($cookie), time()+(86400/86400*30) );
}
?>
//to print the values
<?php
if (isset($_COOKIE[$cookiename]) ) {
print_r(unserialize($_COOKIE[$cookiename]));
}
?>
With unserialize you can store a multiple dimension array into a cookie with no problem.

Using apply_filters inside an add_action function not applying filter changes

I have a plugin, and I'm using add_action to hook into auth_cookie_valid to alter how login cookies are handled.
I want to create a filter inside the hook to allow users to control the logic a little.
I have this inside my auth_cookie_valid hook which has the default value false, then applies the filter:
$allowDuplicateSessions = false;
$allowDuplicateSessions = apply_filters('persistent_login_allow_duplicate_sessions', $allowDuplicateSessions);
and in functions.php I have this to make it true:
function handle_persistent_login_allow_duplicate_sessions($allowDuplicateSessions) {
$allowDuplicateSessions = true;
return $allowDuplicateSessions;
}
add_filter('persistent_login_allow_duplicate_sessions', 'handle_persistent_login_allow_duplicate_sessions');
However, $allowDuplicateSessions always returns false.
I'm wondering if the filter in functions.php is running too late for the auth_cookie_valid hook? I haven't spotted anything in the documentation though.
I think this because I moved my apply_filters code to the wp_footer action hook and it returned true. So I'm starting to think that the issue is with auth_cookie_valid?
Function as requested below (I've removed a lot of irrelevant lines as it's quite a big function:
// update auth cookie with new login time, expiry time & IP address
function persistent_login_update_auth_cookie($cookieElements, $user) {
if( $user ) :
$persistent_login_roles = get_option( 'persistent_login_options_user_access' );
if( $persistent_login_roles ) :
if( array_intersect($user->roles, $persistent_login_roles) ) :
// update the cookie expiration time
$options = get_option('persistent_login_options_premium');
if( $options ) :
$expiration = $options['cookieTime'];
else :
$expiration = strtotime('1 year', 0); // 1 year default
endif;
// update the IP address and login time of the cookie
$sessionToken = $cookieElements['token'];
if ( function_exists( 'hash' ) ) :
$verifier = hash('sha256', $sessionToken);
else :
$verifier = sha1( $sessionToken);
endif;
$sessions = get_user_meta($user->ID, 'session_tokens', true);
$sessions[$verifier]['login'] = time();
$sessions[$verifier]['expiration'] = time()+$expiration;
$sessions[$verifier]['ip'] = $_SERVER["REMOTE_ADDR"];
// update the token with new data
$wp_session_token = WP_Session_Tokens::get_instance($user->ID);
$wp_session_token->update( $sessionToken, $sessions[$verifier]);
// apply filter for allowing duplicate sessions
$allowDuplicateSessions = false;
$allowDuplicateSessions = apply_filters('persistent_login_allow_duplicate_sessions', $allowDuplicateSessions);
// remove any exact matches to this session
foreach ($sessions as $key => $session) :
if( $key !== $verifier ) :
if( is_bool($allowDuplicateSessions) ) :
if( $allowDuplicateSessions === false ) :
// if we're on the same user agent and same IP, we're probably on the same device
// delete the duplicate session
if(
($session['ip'] === $sessions[$verifier]['ip']) &&
($session['ua'] === $sessions[$verifier]['ua'])
) :
$updateSession = new Persistent_Login_Manage_Sessions($user->ID);
$updateSession->persistent_login_update_session($key);
endif;
endif;
else :
return new WP_Error( 'broke', __( "Error, expected boolean value in persistent_login_allow_duplicate_sessions filter." ) );
endif; // end boolean check
endif; // if key is different to identifier
endforeach;
// set users local cookie again - checks if they should be remembered
$rememberUserCheck = get_user_meta($user->ID, 'persistent_login_remember_me', true);
if( $rememberUserCheck === 'true' ) :
// if the user should be remembered, reset the cookie so the cookie time is reset
wp_set_auth_cookie($user->ID, true, is_ssl(), $sessionToken);
else :
// if the users doen't want to be remembered, don't re-set the cookie
endif;
endif; // end if roles match the user roles
endif; // endif persistent login roles
endif; // endif user
}
add_action('auth_cookie_valid', 'persistent_login_update_auth_cookie', 10, 2);

PHP - If an array contains part of a string

I have the following PHP code:-
<?php
if( have_rows('postcode_checker', 'option') ):
while ( have_rows('postcode_checker', 'option') ) : the_row(); ?>
<?php
$postcodes .= get_sub_field('postcodes');
$postcode_url = get_sub_field('page');
?>
<?php endwhile;
else : endif;
$postcode_array = $postcodes; // This collects postcodes, i.e. LE67, LE5 etc...
$postcode_array = explode(',', $postcode_array);
$postcode_array = str_replace(' ', '', $postcode_array);
$postcode_search = $_POST['postcode']; // This will be a single postcode i.e. LE67
if (in_array($postcode_search, $postcode_array)) {
echo 'yes';
} else {
echo 'no';
}
?>
So the code above is working fine if I want to look up say LE67 and it finds LE67 in the array and returns 'yes'. Now if I search LE675AN for example it will return no even though it needs to be returning yes as it is within the postcode area.
Any idea's on how I can achieve this?

Handling sessions with procedural PHP

I would like to dedicate this page to handling sessions using procedural php.
I'll begin with how I start most of my projects:
session_name('Easy_App');
session_start();
if (!isset( $_SESSION['ip'] )){
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}
if (!isset( $_SESSION['created'] )){
$_SESSION['created'] = time();
}
if (!isset( $_SESSION['overall_views'] )){
$_SESSION['overall_views'] = 1;
}
else {
$_SESSION['overall_views']++;
}
if (!isset( $_SESSION['username'] )){
$_SESSION['username'] = "";
}
if (!isset( $_SESSION['logged_in'] )){
$_SESSION['logged_in'] = 0;
}
/*A quick method to keep pageviews to < 5 pages per 1 second per session*/
if (!isset($_SESSION['first_action'])){
$_SESSION['first_action'] = time();
}
$first_action = $_SESSION['first_action'];
if (!isset( $_SESSION['action'] )){
$_SESSION['action'] = 1;
}
else{
$_SESSION['action']++;
}
$action=$_SESSION['action'];
if ($action>=5){
unset($_SESSION['action']);
unset($_SESSION['first_action']);
if((time() - $first_action) <=1){
exit("Please Don't Hammer My Site ");
}
}
So We have a starting point:
The Start of a session with a few regularly used parameters
In the last few lines, prevention of hammering by casual users.
My question is this:
Where would you go from here? Improvements of the above code or a brief snippet of how you handle sessions using procedural php would be greatly appreciated.
Your code would not work If you are trying to STOP Hammer or FLOODING if the user doesn't keep cookies your Sessions are useless and the script is a waste ... you should try better approach using storage systems like memcache , mongoDB or redis
See : https://stackoverflow.com/a/10155437/1226894 .... this has been answered before
EDIT 1
Am not sure what you want by procedural PHP but i hope this helps
Objectives
Remove duplicate isset
Remove duplicate if Statement
Create single function to get and set $_SESSION
Trying to make everything a function and hide all variables
Final Code
session_start ();
include("procedural.function.php");
__SESSION ( 'ip', $_SERVER ['REMOTE_ADDR'] );
__SESSION ( 'created', time () );
__SESSION ( 'overall_views', 1 );
__SESSION ( 'overall_views', "++" );
__SESSION ( 'username', "" );
__SESSION ( 'logged_in', 0 );
__SESSION ( 'first_action', time () );
__SESSION ( 'action', "++" );
if (__SESSION ( 'action' ) >= 5) {
__UNSET ( 'action' );
__UNSET ( 'first_action' );
if ((time () - __SESSION ( 'first_action' )) <= 1) {
exit ( "Please Don't Hammer My Site " );
}
}
procedural.function.php
function __SESSION($var, $value = null) {
if ($value === null) {
return isset ( $_SESSION [$var] ) ? $_SESSION [$var] : null;
} else if ($value === "++") {
isset ( $_SESSION [$var] ) ? $_SESSION [$var] ++ : $_SESSION [$var] = 0;
return $_SESSION [$var];
} else {
isset ( $_SESSION [$var] ) ? $_SESSION [$var] = $value : null;
return $value;
}
}
function __UNSET($var) {
unset ( $_SESSION [$var] );
}

How can I rewrite this code to improve its clarity?

Could you write this 'cleaner' ? Just a simple question from a beginner:)
if(isset($_GET['tid']) && trim($_GET['tid'])!==""){
$act = 'tid';
$tid = trim($_GET['tid']);
}elseif(isset($_GET['fid']) && trim($_GET['fid'])!==""){
$act = 'fid';
$fid = trim($_GET['fid']);
}elseif(isset($_GET['mid']) && trim($_GET['mid'])!==""){
$act = 'mid';
}elseif(isset($_GET['act']) && trim($_GET['act'])!==""){
$act = trim($_GET['act']);
}else{
$act = "";
}
I would do it like this:
$tid = isset( $_GET['tid'] ) ? trim( $_GET['tid'] ) : '';
$fid = isset( $_GET['fid'] ) ? trim( $_GET['fid'] ) : '';
$mid = isset( $_GET['mid'] ) ? trim( $_GET['mid'] ) : '';
$act = isset( $_GET['act'] ) ? trim( $_GET['act'] ) : '';
if ( empty( $act ) ) // act not set, construct the act from the other GET vars
{
if ( !empty( $tid ) )
$act = 'tid';
else if ( !empty( $fid ) )
$act = 'fid';
else if ( !empty( $mid ) )
$act = 'mid';
}
edit: Of course you could make this even shorter, but the question was how it could be written to “improve its clarity”. And I understand clarity as something that makes it more easy to understand, what happens in a part of code. And I think the actual logic behind the original code gets quite clear with my solution.
I see nothing bad in your code apart from lack of indentation:
if(isset($_GET['tid']) && trim($_GET['tid'])!==""){
$act = 'tid';
$tid = trim($_GET['tid']);
}elseif(isset($_GET['fid']) && trim($_GET['fid'])!==""){
$act = 'fid';
$fid = trim($_GET['fid']);
}elseif(isset($_GET['mid']) && trim($_GET['mid'])!==""){
$act = 'mid';
}elseif(isset($_GET['act']) && trim($_GET['act'])!==""){
$act = trim($_GET['act']);
}else{
$act = "";
}
Although perhaps you could benefit from a function like this
function get_non_empty($field){
return isset($_GET[$field]) && trim($_GET[$field])!='' ? $_GET[$field] : NULL;
}
Definitely not the 'cleanest' solution, but a lot shorter:
$act = '';
foreach(array('tid', 'fid', 'mid', 'act') as $a) {
if(isset($_GET[$a]) && strlen(trim($_GET[$a])) > 0) {
$$a = trim($_GET[$act = $a]);
break;
}
}
This is nearly identical logically to what poke did (+1 for poke for beating me to it), but since we're talking about clarity I thought I'd show my take on it. I like to use FALSE instead of empty strings when it means something isn't being used. It feels like a more explicit way of saying "no". Also, I rarely use the non-bracketed version of if/else but for really short assignment statements I find it way easier to read.
$tid = isset($_GET['tid']) ? trim($_GET['tid']) : FALSE;
$fid = isset($_GET['fid']) ? trim($_GET['fid']) : FALSE;
$mid = isset($_GET['mid']) ? trim($_GET['mid']) : FALSE;
$act = isset($_GET['act']) ? trim($_GET['act']) : FALSE;
if ($act){ // act not set, construct the act from the other GET vars
if ($tid) $act = 'tid';
else if ($fid) $act = 'fid';
else if ($mid) $act = 'mid';
}
Careful with those raw GET values. You should clean those values up before processing them to make sure you are getting exactly what you want, especially if this is about to insert values to a database.
Here is one way. I would however probably do something differently with the tid,fid,mid stuff if I knew what they was intended for.
list($act,$val) = firstValidGETIn('tid','fid','mid','act');
switch($act) {
case 'act': $act = $val; break;
case null : $act = ""; break;
default : $$act = $val;
}
function firstValidGETIn()
{
foreach(func_get_args() as $key)
{
if(array_key_exists($key,$_GET) && trim($_GET[$key]))
return array($key, trim($_GET[$key]));
}
return array(null,null);
}

Categories