php & cookies : last $articleid visited in an array - php

I have very little experience with cookies so I don't know how to do that.
I have a t-shirt shop where each t-shirt has an $articleID.
Each time an user visits a t-shirt page, I would like to add the $articleID to a cookie.
Then add it to an array or something so I can retrieve it later.
There shouldn't be any duplicate $articleID even if the visitor visited the same $articleID twice.
Then on the main page, I want to retrieve the list of the last 5 $articleID visited and display a list of the ID.
How could I do that?
Thanks!

in order to store an array in your cookies you will need to serialize it so check if this code will help
$articles = array();
if ( isset($_COOKIE["viewed_articles"]) )
$articles = unserialize($_COOKIE["viewed_articles"]);
if ( ! in_array($articleID, $articles)){
$articles[] = $articleID;
}
// at the end update the cookies
setcookie("viewed_articles", serialize($articles));
I hope this helps and have a loop at this link

Something like this?
<?php
$article_id = 1; // Whichever article you're currently viewing
session_start();
if ( ! isset($_SESSION['viewed_articles']))
{
$_SESSION['viewed_articles'] = array();
}
if ( ! in_array($article_id, $_SESSION['viewed_articles']))
{
$_SESSION['viewed_articles'][] = $article_id;
}

Have you tried using Sessions? Cookies will store the values on the users computer. That data is transferred to your web server on every page load.
Sessions store data on the server side. Sessions work by storing a session ID as a cookie on the user's browser which corresponds to a session stored on the server.
If you are using PHP, you can initiate a session by using
<?php
session_start();
$_SESSION['key'] = 'value';
echo $_SESSION['key']; // outputs: value
?>

Related

PHP Cookies Show Login Account List Gmail Like

I would like to implement multiple user login show like gmail login. See below image:
Current I'm using COOKIE to get the USERID. But it only give me the last USERID. not all.
Here is PHP to set COOKIE:
setcookie("cookielogin[userLoginRemembered]", $dataLoginQuery['USERID'] , $time + (60*60*24*7));
What I want is, to show all user ever logged in and display it using COOKIE.
Is it possible?
Because you only store last logged user id into cookie, and it overrides old value
Cookie only stores raw text, so if you want to store a list (array), you have to serialize it (by your own way or using serialize() function). This
sample code below uses PHP's serialize():
$lastLoggedUserId = '123';
if (!isset($_COOKIE['cookie_key_for_logged_users'])) {
$cookieLoggedUserIds = [$lastLoggedUserId];
} else {
// unserialize
$cookieLoggedUserIds = (array) unserialize($_COOKIE['cookie_key_for_logged_users']);
$cookieLoggedUserIds[] = $lastLoggedUserId;
}
// just to make sure no duplicated user id to be stored
$cookieLoggedUserIds = array_unique($cookieLoggedUserIds);
setcookie('cookie_key_for_logged_users', serialize($cookieLoggedUserIds));
print_r(unserialize($_COOKIE['cookie_key_for_logged_users']));
I've not tested this code, but it's easy to test and tweak.
You need to append the information in the cookie.
There is no append for cookies so what we need to do is read it's current value, add current string and write a new cookie.
$currentvalue = $_COOKIE["cookielogin[userLoginRemembered]"];
If(strpos($currentvalue, $dataLoginQuery['USERID']) !== false){
Echo "username exist in cookie already";
}else{
setcookie("cookielogin[userLoginRemembered]", $currentvalue .",". $dataLoginQuery['USERID'] , $time + (60*60*24*7));
//Here I set the value of cookie as current value and dataloginquery.
}
Output:
Var_dump(explode(",", $_COOKIE["cookielogin[userLoginRemembered]"]));
// Dumps the array of usernames that is comma separated.

Store Two Dimensional Array in Session PHP

I've been searching for this solution for a while now and found some thread that were made previously regarding my same problem. But I still could not solve my problem. It's been days now and I still can't keep the array data from my HTML form to be stored in session. It just get overwritten every single time. Is there something wrong my my coding?
This is my PHP file that processes the input
<?php
if(!isset($_SESSION)){
session_start();
}
$student1 = array(
array(
'Name'=>$_POST['name'],
'Matric-No'=>$_POST['matric'],
'Gender'=>$_POST['gender'],
'Day'=>$_POST['DOBDay'],
'Month'=>$_POST['DOBMonth'],
'Year'=>$_POST['DOBYear'],
'Citizen'=>$_POST['citizen'],
'Marital'=>$_POST['kahwin'],
'Religion'=>$_POST['religion'],
'Active'=>$_POST['active'],
'Year-of-Study'=>$_POST['Cyear'],
'ID-Number'=>$_POST['idno'],
'Email'=>$_POST['email']
)
);
$_SESSION['data'] = $student1;
print_r($_SESSION);
?>
*Edit: So sorry... I forgot to mention that I do have a javascript validator to see if the user has successfully entered every form before submitting. And my problem is that when I refresh or go back to the form site, the previous data will not be there and if there is any new data that is entered. The previous data will be overwritten
You must set the $_SESSION['data'] only if a form has been submitted. Here is an example testing if name and religion has been sent (You could test for all variables to be sure):
session_start();
if ( isset( $_POST['name'] && isset( $_POST['religion'] ) {
$student1=array(
'Name'=>$_POST['name'],
'Matric-No'=>$_POST['matric'],
'Gender'=>$_POST['gender'],
'Day'=>$_POST['DOBDay'],
'Month'=>$_POST['DOBMonth'],
'Year'=>$_POST['DOBYear'],
'Citizen'=>$_POST['citizen'],
'Marital'=>$_POST['kahwin'],
'Religion'=>$_POST['religion'],
'Active'=>$_POST['active'],
'Year-of-Study'=>$_POST['Cyear'],
'ID-Number'=>$_POST['idno'],
'Email'=>$_POST['email']
);
$_SESSION['data']=$student1;
}
print_r($_SESSION);
?>
Now the $_SESSION['data'] is only changed when you POST a form with name and religion!
EDIT:
If you want to add more than one student in the session, try something like this:
$_SESSION['data'][]=$student1;
or simply:
$_SESSION['data'][]=$_POST;
To retrieve the data you do something like this:
foreach ( $_SESSION['data'] as $data )
echo 'Name: ' . $data['Name'];
or
for( $i = 0; $i < count( $_SESSION['data'] ); $i++ )
echo 'Name: ' . $_SESSION['data'][$i]['Name'];
Edit 2 Removed extra array from $student1 variable
You are missing session_start() to start session itself.
And make queries such $_SESSION['data'] = [your_array]; and test as isset($_SESSION['data'])
Check this page http://php.net/manual/en/ref.session.php

how can i track last 5 pages visited using cookies in php

<?php
session_start();
if(empty($_SESSION['track']))
$_SESSION['history'] = array($_SERVER['PHP_SELF']);
else {
$_SESSION['track'][] = $_SERVER['PHP_SELF'];
if(count($_SESSION['track']) > 5)
array_shift($_SESSION['track']);
}
function display()
{
print_r(array_values($_SESSION['track']));
}
?>
i was able to do it using session but i need to use only cookies and php to track the last 5 pages visited.
any idea guys??
Any comment or answer will appreciate. Thanking in advance.
$url = unserialize($_COOKIE['history']);
array_push($url,your_url);
setcookie('history', serialize($url));
onload of every page first retrieve the value of cookie in url and push the current url in it and add set it to cookie

how to store recently viewed products in cookie in php

I want to show recently viewed products in my application with the help of cookies in php.I m able to create a cookie and store it.But i m not aware about how to store viewed products in cookie and whenever user comes later on after first time.He should be able to see the recently viewed products if any.
Following is the code for cookie creation and checking the cookie name if exists..
<?php
session_start();
$ID=$_GET['id'];
echo $ID;
$array1=array();
$cookie=array();
if (isset($_COOKIE['mycookie'])) {
$cookie[] = $ID;
$cookie = $_COOKIE['mycookie'];
$cookie = unserialize($cookie);
} else {
$cookie=array();
$cookie[] = $ID;
$cookie = serialize($cookie);
// cookie not set, so let's "tag" this visitor
setcookie('mycookie',$cookie);
// display page for first time visitors
}
Please guide on how to show recently viewed products in addition to this cookie creation....

Change session ID and keep data?

When a user logs in on our website, I want to change the session ID but keep whatever data is in the session. I want to do this for two reasons:
To prevent a user account to be used at multiple places simultaneously (because if two people are using the same account, the actions of one will undermine the actions of the other).
To let the user continue what he/she was doing on another computer (e.g moving from home computer to work).
These might seem contradictory, but really aren't if you think it through.
The problem is as follows; to get to the data that is currently in the session, I have to call session_start(). This means I cannot call session_id() afterwards to set a new session ID. Any ideas how to transfer the session data and change the session ID.
Update: I need to be able to choose the session ID myself. session_regenerate_id() therefore won't work.
You might be able to use session_regenerate_id():
<?php
session_start();
$old_sessionid = session_id();
session_regenerate_id();
$new_sessionid = session_id();
echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";
print_r($_SESSION);
?>
or even a cruder approach might work:
// save the session
session_start();
$session = array();
foreach ($_SESSION as $k => $v) {
$session[$k] = $v;
}
session_commit();
// create new session and copy variables
session_id("new session id");
session_start();
foreach ($session as $k => $v) {
$_SESSION[$k] = $v;
}
Use this. Put it to a function:
function update_session($newsessid = '') {
// Backup the current session
$session_backup = $_SESSION;
// Set current session to expire in 1 minute
$_SESSION['OBSOLETE'] = true;
$_SESSION['EXPIRES'] = time() + 60;
// Close the current session
session_write_close();
// Set a new session id and start the session
$newSession = session_id($newsessid);
session_start();
// Restore the previous session backup
$_SESSION = $session_backup;
// Clean up
unset($session_backup);
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}
You would then call it when required:
update_session($customid);
Or, you may just be able to use something like this:
$path=session_save_path();
$whatever_session_id;
pass these variables to the next page:
session_id()=$whatever_session_id;
session_save_path()=$path;
You'd be setting the path of the new session id to the old session data....
I don't know if this is really what you'd want, be here it is.

Categories