PHP cookies, add more values to attribute - php

I'm trying to implement the following feature. When someone reads an article, I want to add a cookie that stores the article id so I can use this in another page. My issue is that if the user sees another article, then the cookie is rewritten so the old id is deleted. I want to keep in the cookie all the ids of the seen articles.
Setting the cookie
<?php
// Check if cookie exists
if( isset($_COOKIE["read"]) ) {
$array = unserialize($_COOKIE['read']);
// Iterate array
found = False;
foreach ($array as $i) {
// Check if doc id already in cookie
if ($array[$i] == $id) {
found = True;
}
}
if (!found) {
array_push($array, $id);
setcookie("read", serialize($array), time()+3600);
}
}
// If cookie does NOT exists
else {
$array = array();
array_push($array, $id);
setcookie("read", serialize($array), time()+3600);
}
?>
Reading the cookie to show that the article is read
<?php
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
if( isset($_COOKIE["read"]) ) {
$array = unserialize($_COOKIE['read']);
// Iterate array
for ($i = 0; $i < count($array); ++$i) {
if ($array[$i] == $id) {
$read = True;
}
else {
$read = False;
}
}
}
else {
$read = False;
}
print "<p>Document ".$row['id']." Title: <b>".$row['title']."</b>";
if ($read == True) {
print("*");
}
print " More Info</p>";
}
?>
This code works but as said overwrites the previous article id. I think I got to use an array. But I don't know how to keep adding values.
UPDATE: I tried to serialize but still no results. I'm trying to see if the id is inside the unserialized array.

Do you want Arrays in cookies PHP
Serialize data:
setcookie('cookie', serialize($idS));
Then unserialize data:
$idS= unserialize($_COOKIE['cookie']);

Try adding a datetime() string to the start of the cookie's name. That way old ones won't get overwritten. Something like:
$date_snippet = date('Y-m-d H:i:s');
setcookie("{$date_snippet}read", serialize($array), time()+3600);

Related

How to start a foreach loop with a specific value in PHP?

I need to start a for each loop at certain value, ex foreach($somedata as $data) Here I want to start doing some stuff only when the value of that data is "something"
I want to start doing something only after a specific value.
foreach($somedata as $data){
if($data == 'Something'){
//start processing, ignore all the before elements.
}
}
I tried break continue nothing seems to work as I wanted
For clarity, it's probably better to pre-process your array before looping over it. That way the logic inside your loop can purely focus on what it's supposed to do.
$arr = ['foo', 'something', 'bar'];
$toProcess = array_slice($arr, array_search('something', $arr));
foreach ($toProcess as $element) {
echo $element, PHP_EOL;
}
outputs
something
bar
How about using a indicator variable to achieve this.
$starter = 0;
foreach($somedata as $data){
if($data == 'Something'){
$starter = 1;
}
if(starter == 1){
//start processing, ignore all the before elements.
}
}
You'll need to keep a flag whether you have already encountered the desired value or not:
$skip = true;
foreach (... as $data) {
if ($data == 'something') {
$skip = false;
}
if ($skip) {
continue;
}
// do something
}
$skip = true;
foreach($somedata as $data){
if($data == 'Something'){
$skip = false;
}
if($skip) {
continue;
}
//start processing, ignore all before $skip == false.
}
If you want to process the values only from the moment you identify one value, then you can use a flag :
$flag = false;
foreach($somedata as $data){
if($flag OR $data == 'Something'){
$flag = true;
// processing some stuff
}
}
Once the flag is reset to true, whatever the current value is, the content of your if will be executed.

Store array of objects in PHP session

How can I store/remove/get an array of objects in the PHP session?
I tried this for adding:
array_push($_SESSION['cart'], serialize($item));
and this for removing:
function removeitem ($item)
{
$arrayCart = $_SESSION['cart'] ;
for ($i=0; $i<$arrayCart.length; $++ )
{
if ($item.id == $arrayCart[i].id)
$arrayCart.splice (i,0);
}
}
But it doesn't work!!
<?php
session_start();
$_SESSION['cart']=array();
$_SESSION['cart']['username'] = 'Admin';
$_SESSION['cart']['Password'] = '123';
.
.
.
?>
For Remove
<?php
session_start();
$_SESSION['cart']=array();
unset ( $_SESSION['cart']['username'] );
.
.
or use Custom Function to Remove...
.
?>
It's Work For Me...
if this code Report Errors Please Comment to Check this...
Please check PHP version
How has no one seen this:
for ($i=0; $i<$arrayCart.length; $++ ){ // <----- lol # $++
Make it $i++
You also need another 2 } to close your if() and for() statements so it's like this:
function removeitem ($item){
$arrayCart = $_SESSION['cart'] ;
for ($i=0; $i<$arrayCart.length; $++ ){
if ($item.id == $arrayCart[i].id){
$arrayCart.splice (i,0);
}
}
}
Have you tried using this?
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = [];
}
$_SESSION['cart'][] = $item;
You don't need to serialize the item-variable - a Session can store pure Objects, as long as the max. session-size doesn't exceed.
If you want to remove Items from the cart, you should use index-Names - this allows you to find your items faster.
I would probably use something like this:
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = [];
}
function addItem($itemName){
if(!isset($_SESSION['cart'][$itemName])) {
$_SESSION['cart'][$itemName] = 1;
}else
$_SESSION['cart'][$itemName] ++;
}
}
function removeItem($itemName){
if(isset($_SESSION['cart'][$itemName])) {
if($_SESSION['cart'][$itemName] > 0) {
$_SESSION['cart'][$itemName] --;
}
}
}
function clearCart(){
unset($_SESSION['cart']);
}
In this case, the cart stores each item and its amount. Instead of $itemName, you could also use the item-ID from your database.
To get an item from the cart, you will need this function:
function getItemCount($itemName){
if(isset($_SESSION['cart'][$itemName])) {
return $_SESSION['cart'][$itemName];
}
return 0;
}
Try not pushing to array, because its probably not set yet, but to store to session, create new session var by:
$_SESSION['cart']=serialize($item);
to remove it:
unset($_SESSION['cart']);
EDIT:
Thanks to comments I realized that above code wouldn't store array in session. So, another short solution is to store to session var some JSON. Try this for a short test:
$tmp = array(1,2,3);
$_SESSION['cart']=json_encode($tmp);
print_r(json_decode($_SESSION['cart']));
If that array is associative, you shoud use for decode:
json_decode($_SESSION['cart'], true);

Shuffle array values every time when page opened, no sessions ?

I have a database with some questions and I want every time the page is opened, not refreshed to show them in different order.
The shuffling, it's ok :
function shuffle_keys( &$array ) {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
}
Shuffle the array with values from database and printing it:
shuffle_keys($array_questions);
foreach( $array_questions as $key => $val ) {
$key_value = ++$key;
echo "<a href = '?id=$val'>".$key_value."</a> ";
}
Just now, when I refresh every time the shuffling is different I want it this way only when I first open the page.
If you want to have the same shuffling for the same session, (that's what I understood)
You can use a $_SESSION variable to store your array.
session_start();
if (isset($_SESSION['array_questions']))
$array_questions=$_SESSION['array_questions'];
else
{
shuffle_keys($array_questions);
foreach( $array_questions as $key => $val ) {
$key_value = ++$key;
echo "<a href = '?id=$val'>".$key_value."</a> ";
}
$_SESSION['array_questions']=$array_questions;
}
You cannot detect a page refresh on its own. Perhaps consider setting a cookie and asserting whether it exists on page open?
You can use a static variable for the purpose. Just create a class as below:
class Base {
protected static $variable = 0;
}
class child extends Base {
function set() {
self::$variable = 1; // let say 1 = 'sorted'
}
function show() {
echo(self::$variable);
}
}
Now when you enter your site,
Create an object and set the variable, calling the method
$c1 = new Child();
if($c1->show() == 0)
{
// sort your array here and set the static flag to sorted(1)
$c1->set();
}
Hope this help...

php array, to check if a value at key is set or not and update accordingly

I initialize a php array named $present, the purpose of this array is to hold the value of 1 if a name is present or zero if the name is absent. i have a name array of size 10. below is the code mentioned, but it is not working.
$present = Array();
for($i=0;$i<=10;$i++){
if(!isset($present[$name[$i]])) {
$present[$name] = 1;
}
else echo $present[$name[$i]];
}
i have also tried this :
$present = Array();
for($i=0;$i<=10;$i++){
if(empty($present[$name[$i]])) {
$present[$name] = 1;
}
else echo $present[$name[$i]];
}
please help thanks!
I think this may be what you are looking for. You're missing the $i when setting it to 1.
$present = array();
for($i=0;$i<=10;$i++){
if(!isset($present[$name[$i]])) {
$present[$name[$i]] = 1;
}
else echo $present[$name[$i]];
}
Should be:
$present = Array();
for($i=0;$i<10;$i++){
if(!isset($present[$name[$i]])) {
$present[$name[$i]] = 1;
}
else echo $present[$name[$i]];
}
I'm not sure exactly what you're trying to do here, but if you just want to keep track of whether a name is present or not, you could just make $present be an array of names, and then use in_array.
$present = array('John', 'Paul', 'George');
echo in_array('John', $present); # returns 1
echo in_array('MacArthur', $present); #returns 0

Check Sessions in an array?

hmm i got a homework, its 2 hours and i still have no clue on it :|
like this
$sessions['lefthand'] = 'apple';
$sessions['righthand'] = '';
$sessions['head'] = 'hat';
$sessions['cloth'] = '';
$sessions['pants'] = '';
// here is the homework function
CheckSession('lefthand,righthand,head,cloth,pants');
we have some string "lefthand,righthand,head,cloth,pants"
question is : " how can we check if the five session is not null or exist and display which session is empty ( if there is an empty session ) if all exist then returns a true ?
empty righthand , pants, and cloth.
this is how i think about it
explode it to arrays
check one bye one if !null id there is a
here is the progress that ive made *edit4 , :)
function CheckSession($sessions){
$all_sessions_exist = true;
$keys = explode(',',$sessions);
$error = array();
// Search for Session that are not exist
foreach ($keys as $key) {
if (!isset($_SESSION[$key]) && empty($_SESSION[$key])) {
echo "no $key</br>";
$all_sessions_exist = false;
}
}
return $all_sessions_exist;
}
Thanks for taking a look
Adam Ramadhan
Seeing as it's homework, you won't get the solution. You're on the right track though. explode() it by the delimiter. You can the loop through it using foreach and use empty() to check if they're set. You can access the sessions like $_SESSION[$key]. Keep an array of the ones that match.
function CheckSession($string){
$all_sessions_exist = true; #this will change if one of the session keys does not exist
$keys = explode(',', $string); #get an array of session keys
foreach($keys as $key){
if(isset($_SESSION[$key])) {
if(!empty($_SESSION[$key]))
echo '$_SESSION['.$key.'] is set and contains "'.$_SESSION[$key].'".'; #existing non-empty session key
else echo '$_SESSION['.$key.'] is set and is empty.' ;
}else {
echo '$_SESSION['.$key.'] is not set.'; #key does not exist
$all_sessions_exist = false; #this will determine if all session exist
}
echo '<br />'; #formatting the output
}
return $all_sessions_exist;
}
Just cleaning up your function
function CheckSession($sessions)
{
$session = explode(',',$sessions);
$return = array();
foreach ($session as $s)
{
$return[$s] = (isset($_SESSION[$s]) && !empty($_SESSION[$s]) ? true : false)
}
return $return;
}
$sessions['lefthand'] = 'apple';
$sessions['righthand'] = '';
$sessions['head'] = 'hat';
$sessions['cloth'] = '';
$sessions['pants'] = '';
And the checking part
// here is the homework function
$Results = CheckSession('lefthand,righthand,head,cloth,pants');
Edit
//$value1= false; // Commented out so does not get set
$value2= false; //Still set to a bool
error_reporting(E_ALL);
empty($value1); // returns false but still strikes E_NOTICE ERROR
empty($value2); // returns false with no error
Note, empty does not trigger an error but this example would take affect an a lot of other php functions.

Categories