PHP store old value and compare with new one - php

I have a webpage that refreshes every X minute and shows some information from an array.
Name Value
-------------
Mark 546
Donald 312
My question is what is the easiest way to temporarily store the old value and compare it to the new value between page refreshes (see below)? It could be per user based simply when visiting the page. Php session and cookies maybe?
Name Value Change
--------------------
Mark 559 +13
Donald 233 -79

So you can easily do it with sessions
//structure in sessions could be like this
$_SESSION['last'] = $data; // all the data you echo
$_SESSION['last']['timestamp'] = $time; //timestamp when you fetched this data
$_SESSION['previous'] = $old_data; // store the last data
// each time last data is older than 5 min, refresh
if (time() - $_SESSION['last']['timestamp'] > 5 * 60){
//store current data as previous
$_SESSION['previous'] = $_SESSION['last'];
//set new data in $data
$_SESSION['last'] = $data; // set all your new data
$_SESSION['last']['timestamp'] = time(); //set timestamp
}

Related

Php: How to store a token and retrieve it for comparing?

Hi I am creating a token to compare against some record on the database to log a user in. I am using token = openssl_random_pseudo_bytes to set this random string, but how its stored on the browser and database seem to be different. How do I compare these two strings?
Set the value token first using a cookie way
$value = "23asdoq23ARDAsdadq2";
// cookie will expire when the browser close
setcookie("tokenCookie", $value);
// cookie will expire in 1 hour or set it to your needs
setcookie("tokenCookie", $value, time() + 3600);
or set the duration to 0, so that cookie duration will end only when users browser is close
setcookie("tokenCookie", $value, 0);
then retrieved the cookie and compare selected token value from the database with the cookie token.
if(!isset($_COOKIE['tokenCookie'])) {
$tokenCookie = $_COOKIE['tokenCookie'];
// Assume you already retrieved the token value from the database and stored it to a variable then you just need to compare it..
if( $tokenCookie == $token_value_from_database ){
echo true;
}else{
echo false;
}
}

Compare time difference

I want to compare the time between sent messages, so that i know how quick someone would respond.
message_sent is the unix timestamp when a message has been sent.
ID: 0000000005 is the start, ID: 0000000006 is a response on the message of ID: 0000000005.
With this data: 0000000006 sent a message on 1483021773. The original question was asked in 0000000005 on 1483021687. So the reaction time is 1483021773 - 1483021687. How should i approach this so i get an average response time?
The data
Assuming that a response time is defined by the time it takes for a user to respond to the last message of another user:
$response_times = array(); // array of response times
// let's define a variable to keep track of the person
// to which another person will respond. initially, variable will hold
// the first message
$initiator = array_shift($messages);
// now iterator through messages
foreach ($messages as $message) {
// if this message belongs to the initiator, just update the timestamp
if ($message['from_user_id'] == $initiator['from_user_id']) {
$initiator['message_sent'] = $message['message_sent'];
continue; // and go to the next message
}
// otherwise, calculate the time difference and put it in response times
array_push($response_times, $message['message_sent'] - $initiator['message_sent']);
// and update the initiator
$initiator = $message;
}
// finally, calculate average of response time
$avg_response_time = array_sum($response_times) / count($response_times);
Since i don't know the exact code here is some sudo code with an example:
$total_items = count($array_of_items);
$starting_time_total = "0";
// Some code here to do your message_sent - message_sent = $some_value;
// Do the following for every single item for the $total_items in array
$starting_time_total = $starting_time_total + $some_value;
//Now to get the average we do this
$average = $starting_time_total / $total_items;
So if you have 4 items in the array, with response times of 423, 395, 283, 583 respectively, you are left with an average response time of 421 which you can then convert to seconds of minutes or whatever.

How to get the latest cookie id without additional page reloading?

There is a page, that can be visited with one of three params: ref1, ref2 and ref3. Each time page script sets a couple of cookies to store ref-param and time of it's creation. After that it should find the latest one and be ready to deal with it.
For example if I have "ref1" cookie as latest before visiting page and visit
script.php?ref2=1
it should echo
latest is ref2
But it works properly (echoes right latest cookie) only after additional reloading of the page. What's wrong with this code?
if ($_GET['ref1']) {
setcookie('ref1', 'ref1');
setcookie('ref1_dt', time());
}
if ($_GET['ref2']) {
setcookie('ref2', 'ref2');
setcookie('ref2_dt', time());
}
if ($_GET['ref3']) {
setcookie('ref3', 'ref3');
setcookie('ref3_dt', time());
}
function getLatestCookie() {
$refs = array(
'ref1' => $_COOKIE['ref1_dt'],
'ref2' => $_COOKIE['ref2_dt'],
'ref3' => $_COOKIE['ref3_dt']
);
$maxs = array_keys($refs, max($refs));
return $maxs[0];
}
$latest = getLatestCookie();
setcookie('latest', $latest, time() + 60 * 60 * 24 * 30, "/");
echo "latest is " . $latest;
As usual, reading docs was good enough.
Cookies are available in $_COOKIE array after next page loading. So in my case I should assign $latest to GET-param value if it exists and else assign it with getLatestCookie().

Does the function "apc_store" reset the TTL values when replacing a cache key that already exist?

I current utilize the APC "apc_store" function as a means to replace items in the cache that already exists, but I'm not sure if the TTL gets reset or not. I'd like to have it so it does NOT reset the TTL values.
The TTL you provided in apc_store will definitely overwrite the TTL of existing item. If you don't provide TTL, the item will never expire.
TTL is relative, number of seconds from now. If you want a fixed value, just use the same value on every apc_store call.
If you want the item expire at an absolute time, you need to store the time with your object and calculate TTL every time. For example,
$obj = apc_fetch($key);
if (!$obj) {
$obj = new MyObject();
$obj->expiry = time() + 24*60*60; // Expires 24 hours later
}
$ttl = $obj->expiry - time();
if ($ttl <= 0) {
// Item expired
} else {
apc_store($key, $obj, $ttl);
}

How to get cookie's expire time

When I create a cookie, how to get cookie's expire time?
Putting an encoded json inside the cookie is my favorite method, to get properly formated data out of a cookie.
Try that:
$expiry = time() + 12345;
$data = (object) array( "value1" => "just for fun", "value2" => "i'll save whatever I want here" );
$cookieData = (object) array( "data" => $data, "expiry" => $expiry );
setcookie( "cookiename", json_encode( $cookieData ), $expiry );
then when you get your cookie next time:
$cookie = json_decode( $_COOKIE[ "cookiename" ] );
you can simply extract the expiry time, which was inserted as data inside the cookie itself..
$expiry = $cookie->expiry;
and additionally the data which will come out as a usable object :)
$data = $cookie->data;
$value1 = $cookie->data->value1;
etc. I find that to be a much neater way to use cookies, because you can nest as many small objects within other objects as you wish!
This is difficult to achieve, but the cookie expiration date can be set in another cookie. This cookie can then be read later to get the expiration date. Maybe there is a better way, but this is one of the methods to solve your problem.
You can set your cookie value containing expiry and get your expiry from cookie value.
// set
$expiry = time()+3600;
setcookie("mycookie", "mycookievalue|$expiry", $expiry);
// get
if (isset($_COOKIE["mycookie"])) {
list($value, $expiry) = explode("|", $_COOKIE["mycookie"]);
}
// Remember, some two-way encryption would be more secure in this case. See: https://github.com/qeremy/Cryptee
When you create a cookie via PHP die Default Value is 0, from the manual:
If set to 0, or omitted, the cookie
will expire at the end of the session
(when the browser closes)
Otherwise you can set the cookies lifetime in seconds as the third parameter:
http://www.php.net/manual/en/function.setcookie.php
But if you mean to get the remaining lifetime of an already existing cookie, i fear that, is not possible (at least not in a direct way).
It seems there's a list of all cookies sent to browser in array returned by php's headers_list() which among other data returns "Set-Cookie" elements as follows:
Set-Cookie: cooke_name=cookie_value; expires=expiration_time; Max-Age=age; path=path; domain=domain
This way you can also get deleted ones since their value is deleted:
Set-Cookie: cooke_name=deleted; expires=expiration_time; Max-Age=age; path=path; domain=domain
From there on it's easy to retrieve expiration time or age for particular cookie. Keep in mind though that this array is probably available only AFTER actual call to setcookie() has been made so it's valid for script that has already finished it's job. I haven't tested this in some other way(s) since this worked just fine for me.
This is rather old topic and I'm not sure if this is valid for all php builds but I thought it might be helpfull.
For more info see:
https://www.php.net/manual/en/function.headers-list.php
https://www.php.net/manual/en/function.headers-sent.php
To get cookies expire time, use this simple method.
<?php
//#############PART 1#############
//expiration time (a*b*c*d) <- change D corresponding to number of days for cookie expiration
$time = time()+(60*60*24*365);
$timeMemo = (string)$time;
//sets cookie with expiration time defined above
setcookie("testCookie", "" . $timeMemo . "", $time);
//#############PART 2#############
//this function will convert seconds to days.
function secToDays($sec){
return ($sec / 60 / 60 / 24);
}
//checks if cookie is set and prints out expiration time in days
if(isset($_COOKIE['testCookie'])){
echo "Cookie is set<br />";
if(round(secToDays((intval($_COOKIE['testCookie']) - time())),1) < 1){
echo "Cookie will expire today.";
}else{
echo "Cookie will expire in " . round(secToDays((intval($_COOKIE['testCookie']) - time())),1) . " day(s)";
}
}else{
echo "not set...";
}
?>
You need to keep Part 1 and Part 2 in different files, otherwise you will get the same expire date everytime.

Categories