First 2 cookies work, third does not - php

This has got me puzzled, and although it's likely an oversight, I need some fresh eyes please.
session_start();
if( !isset( $_COOKIE['cookie1'] ) ) {
if( !isset ( $_GET['getvar1'] ) ) {
$_SESSION['var1'] = 0;
} else {
$var1 = (int) $_GET['getvar1'];
$_SESSION['var1'] = $var1;
setcookie('cookie1', $var1, ( time() + 604800 ), '/', '.domain.com', false, true );
}
} else {
$_SESSION['var1'] = $_COOKIE['cookie1'];
}
First several work [cookie(n)/getvar(n)/var(n)], but then the next doesn't work. I copied the first statement twice, renaming – which was the first place I checked and had checked by another colleague.
I've even checked some of the sites that check where you are on your cookie limits and still nothing.
Thanks.

Related

PHP Not Running On Page Until Refresh

bit of a strange one that I've not been able to resolve for months so I finally have given in and have come here for the answer. Hopefully.
I have the below shortcode that when ran returns the phone number depending on what variable has a value. This PHP code works as expected, the one thing that doesn't work as expected however, is the first ever page load.
When someone goes to the site for the first time (or in incognito mode) the shortcode doesn't output anything, however, refresh the page just once and it'll display the output of the correct value and I have no idea why.
<?php function gw_cookie($atts) {
extract(shortcode_atts(array(
"value" => ''
), $atts));
$getVariable = isset($_GET[$value]) ? $_GET[$value] : '';
$newGetVariable = str_replace('_', ' ', $getVariable);
$cookiePhone = isset($_COOKIE[$value]) ? $_COOKIE[$value] : '';
$acfField = get_field('page_cookie_'.$value.'');
$optionsACF = get_field('options_company_details', 'options');
$area = $optionsACF['options_area'];
$phone = $optionsACF['options_telephone'];
if(!empty($cookiePhone) && $cookiePhone !== 'undefined') { //If cookie is not empty do the following
echo '1';
} elseif(!empty($newGetVariable)) { //If cookie is empty and get variable is not
echo '2';
} elseif($acfField) { //If ACF field is not empty do the following
echo '3';
} elseif ($value == "phone") {
return '4';
}
} add_shortcode("gw-cookie", "gw_cookie");
This codes file is being imported into the functions.php file using the following line:
require_once( __DIR__ . '/shortcodes/gw-cookies.php' );
A cookie itself would be created on the first run and your criteria requires cookiePhone which is why you have to refresh to make it work.
As per the comments, change:
$cookiePhone = isset($_COOKIE[$value]) ? $_COOKIE[$value] : '';
to:
$cookiePhone = isset($_COOKIE[$value]) ? $_COOKIE[$value] : NULL;

PHP Session custom class sessions not being set?

I have a custom class I am writing for easier scripting for myself. I generate life spanned sessions and normal sessions (normal life span). So here's my script parts for creating and getting
CREATE
public static function create($session_name,$value="") {
//check if the $_SESSION was started manually without using our functions...
if(!isset($_SESSION)) {
//init this- it creates session_start session_id
self::init(self::$settings["default_name"]);
}
//create array for serialization
$new_session = array();
//if our session is an array means we want this session to have some unique properties compared to others
if( is_array($session_name)) {
//store the session value in the array
$new_session["value"] = $session_name["value"];
//total time is null, this indicates if we want a life expectancy of total 10 hours total or total from current time.
$total = null;
if(isset($session_name["lifeclock"])) { //lifeclock should be a hh:mm:ss format to be exploded
$clock = explode(":",$session_name["lifeclock"]); //we've exploded it now assign it
$hours = $clock[0]; //hours
$minutes = $clock[1]; //minutes
$seconds = $clock[2]; //seconds
$session_add = 0; //variable to be added to total or not technically
if(isset($session_name["concurrent"])) {
$session_add = time(); //if concurrent time is true assign time to the session_add
}
$total = ( $session_add ) + ((int)$hours * 60 * 60) + ((int)$minutes * 60) + (int)$seconds; //broken down math to make all seconds
}
if(!isset($total)) { //this is why total is null
$total = self::$settings["lifetime"]; //if null lifetime we'll use the default lifetime
}
session_set_cookie_params( $total, //assing all data to the session_set_cookie_params
isset($session_name["path"]) ? $session_name["path"] : self::$settings["path"],
isset($session_name["domain"]) ? $session_name["domain"] : self::$settings["domain"],
isset($session_name["secure"]) ? $session_name["secure"] : self::$settings["secure"],
isset($session_name["httponly"]) ? $session_name["httponly"] : self::$settings["httponly"]
);
$new_session["life"] = $total; //we'll also add the time and when it was born
$new_session["born"] = time(); // so the user can use this later in the programming code
$_SESSION[$session_name["name"]] = serialize($new_session); //serialize the array
} elseif(is_string($session_name)) {
$new_session["value"] = $value; //assign value value
$new_session["born"] = time(); //assign born time
$_SESSION[$session_name] = serialize($new_session); //serialize the array
}
session_write_close(); //close the lock
}
GET
public static function get($session_name,$data = false) {
//test if session has been opened via manual or programatically
if(!isset($_SESSION)) {
self::init(self::$settings["default_name"]);
}
//if data argument is true meaning we don't want all the extra information we'll just return value!
if($data === false) {
if(isset($_SESSION[$session_name])) {
$sess = unserialize($_SESSION[$session_name]);
if(isset($sess["value"])){
return $sess["value"];
} else return false;
} else return false;
} elseif($data === true) {
return unserialize($_SESSION[$session_name]);
}
}
Now here is my file for testing this altogether.
<?php
set_include_path(dirname($_SERVER["DOCUMENT_ROOT"]));
require "admininit__autoload.php";
Session::configure(array(
"default_name"=>"boogie",
"lifetime"=> 3600,
));
Session::create( array(
"name"=>"my_session",
"value"=>"boogie all night long",
"lifeclock"=>"00:05:00"
));
$session_value = Session::get("my_session");
var_dump($session_value);
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
?>
So this is what I get in response to the var_dump and print_r
bool(false)
Array
(
)
So this tells me that $session_value is return false from the get function meaning altogether that the darn session is not saving for some strange reason. Here is what I see in google developers resource panel as well
So to me that's telling me a session is being created somewhere. I've also went ahead and checked my /tmp folder and see no file starting with sess_ which is the usual file for sessions. Any hints as to where my issue lies or maybe flat out what the hell is wrong here?
Update
While the creation of the code is uncommented out I get this
array(1) {
["my_session"]=> string(88) "a:3:{s:5:"value";s:21:"boogie all night long";s:4:"life";i:300;s:4:"born";i:1431562088;}"
}
string(21) "boogie all night long"
Array
(
[my_session] => a:3:{s:5:"value";s:21:"boogie all night long";s:4:"life";i:300;s:4:"born";i:1431562088;}
)
But when I comment out the creation part it returns this
bool(false)
Array
(
)

Check if each element in an array is a positive, whole number, not a float

To start, I'm still a noob with php, and much of what I've learned is from problems being solved across this site that I have also had myself.
I've found the answers here for all of my original questions, but when I put them all together I can't get get the code to work.
I have a basic form that is posting to itself using PHP_SELF. I want all input from the $_POST array to be checked to make sure that it is (1) a positive integer, (2) a whole number, and (3) does not include a decimal.
if( !empty($_POST ) ) {
foreach( $_POST as $key => $amount ) {
if( !is_int($amount) || $amount < 0 || is_float(amount) ) {
die( 'All data must be positive integers.' );
}
}
}
No matter what I type into any of the input fields it always returns the "die" error.
$amount is a string so is_int will always fail, try filter_var instead
if( !empty($_POST ) ) {
$options = array(
'options' => array(
'min_range' => 0
)
);
foreach( $_POST as $key => $amount ) {
if( filter_var($amount, FILTER_VALIDATE_INT, $options) === false ) {
die( 'All data must be positive integers.' );
}
}
}
is_float(amount)
Should be
is_float($amount)
Typo in your code. Replace is_float(amount) with is_float($amount).
Try this.
if(!empty($_POST)) {
foreach($_POST as $key => $amount) {
if(!(is_int($amount) && $amount >= 0)) {
die( 'All data must be positive integers.' );
}
}
}

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] );
}

PHP Problem: else condition not executing

function procLogin( $user, $pass, $remember, $hostname, $domainame )
{
global $session, $form;
$retval = $session->login( $user, $pass, $remember );
if ( $retval )
{
if ( $session->userlevel == 9 )
if ( $session->isAdmin() )
return ( array(
$session->userlevel, $session->userid
) );
} else {
$process = new process( );
//process->s_Host('domain.com');
//$process->s_Domain('domain.com');
$process->s_Host( $hostname );
$process->s_Domain( $domainname );
$process->s_processSecure( false );
$process->s_User( $user );
$process->s_Pass( $pass );
// First check we actually have a username and password set inside the process object.
if ( $process->g_User() && $process->g_Pass() )
{
if ( $process->processConn() )
{
if ( $process->processBind() )
{
return 'google';
}
}
}
}
}
My problem is if the login is false, why does it not turn towards else condition....
if i remove the code inside else part and put return 'no' it does work.... i just want to know why the code inside the else part does not execute
$session->login(... must somehow always evaluate to true. You would probably be better off posting the code of the login method.
Maybe login is returning "false" as a string? It is evaluating to true because it is not null.
Without a specific error or details of the implementation, or a hint that the PHP runtime or builtin or library is broken ...
This looks like a case of go back, check, debug.

Categories