PHP Add Updated Array to Current Session - php

Ok, so my aim is to add the current profile id ($for) to my session, the aim is for the system to understand which profiles have been viewed in the current session, thus adding to the array. Then it will check the array if it exists and will not show a popup on load as this only needs to happen once.
$for = $_GET['id'];
//GET PREVIOUSLY VIEWED IDS
$prevViewed = $_SESSION['viewedID'];
//THEN ADD THIS PAGE ID TO PREVIOUSLY VIEWED ARRAY
$prevViewed = $for;
//UPDATE SESSION WITH NEW ARRAY INC CURRENT PAGE
$_SESSION['viewedID'] = $prevViewed;
print_r($_SESSION['viewedID']);

How about something like this:
// Make sure that SESSION has the viewedID array
if (!isset($_SESSION['viewedID'])) $_SESSION['viewedID'] = array();
// Store this page in the array
$_SESSION['viewedID'][$for] = true;
You can then check if this page has been viewed with:
if (isset($_SESSION['viewedID'][$for]))
// it has been viewed
else
// it hasn't

I like it, looks like it would work a dream. However, I have fixed it now:
Add to Array the Profile which HAS been viewed...
//ADD THIS PAGE ID TO PREVIOUSLY VIEWED ARRAY
$prevViewed = $for;
//UPDATE SESSION WITH NEW ARRAY INC CURRENT PAGE
$_SESSION['viewedID'][] = $prevViewed;
Check the array for the Current Profile ID...
//CHECK IF CURRENT ID IS NOT IN ARRAY
if(isset($_SESSION['viewedID'])) {
if (!in_array($for, $_SESSION['viewedID'])) {
//PERFORM ACTION IF NOT IN ARRAY
} else {
//PERFORM ACTION IF IS IN ARRAY
}
}
Hope this helps someone.

Related

Cookie array for Recently Viewed - need to extract data from array and cap cookie to 5 IDs

I am trying to create a recently viewed feature to a website. The idea is that you have a box in the right nav that shows your last 3 products viewed. You don't need to be logged it and it's no problem if the user clears cookies, it just starts over.
From what I've researched, the best way to do this is through a cookie array (as opposed to setting 5 cookies or keep adding cookies or doing something in mysql).
I'm having 2 problems:
First, the array keeps adding values, I want it to cap it at 3 values and from there drop the oldest, then add the newest. So, if you visited 7 product page IDs in this order: 100,200,300,400,500,600,150, the cookie should store the values (500,600,150). The first is the oldest of the 3, the last is the newest.
Second, I'm unclear of how to extract the array into something usable. The array is of ID numbers that I guess I need to query against the DB.
When I put this on the page:
COOKIE: <?php echo $cookie; ?>
I get this:
COOKIE: a:7:i:0;s:3:"100";i:1;s:3:"200";i:2;s:3:"300";i:3;s:3:"400";i:4;s:3:"500";i:5;s:3:"600";i:6;s:3:"150";}
This is my code:
//set product id
$product_id = [//some stuff here sets the product id]
// if the cookie exists, read it and unserialize it. If not, create a blank array
if(array_key_exists('recentviews', $_COOKIE)) {
$cookie = $_COOKIE['recentviews'];
$cookie = unserialize($cookie);
} else {
$cookie = array();
}
// add the value to the array and serialize
$cookie[] = $product_id;
$cookie = serialize($cookie);
// save the cookie
setcookie('recentviews', $cookie, time()+3600);
How do I first get the cookie to hold 3 values and drop the oldest?
What is the best way to extract those IDs into something I can put into a query?....str_replace?
This brings up another question, which is should I just put the URL, anchor text, and a couple of attributes of the product into the cookie and not look it up with php/mysql?
As always, thanks in advance.
Here was the answer I ended up figuring out myssef:
// if the cookie exists, read it and unserialize it. If not, create a blank array
if(array_key_exists('recentviews', $_COOKIE)) {
$cookie = $_COOKIE['recentviews'];
$cookie = unserialize($cookie);
} else {$cookie = array();}
// grab the values from the original array to use as needed
$recent3 = $cookie[0];
$recent2 = $cookie[1];
$recent1 = $cookie[2];

Zend Php Foreach Loop array

I have a input field and a array of email from DB table.
I am comparing the similarity of the input field to the array.
But some how, I am stuck with the loop.
Does that loop check compare each email with the input field?
It always bring me to google.com no matter what i input same or not
Here's the code from the controller:
if (isset($_POST['btn_free_download']))
{
// Get current input email from input field
$email = $this->getRequest()->getParam('email');
// Get all emails from the user
$referred_users = $this->_helper->user()->getReferredUsers()->toArray();
// Check the similarity which it with a loop
foreach ($referred_users as $referred_user)
{
similar_text($email, $referred_user['email'], $similar);
}
// If yes, Pop up message or redirect to some page
if ($similar < 97)
{
$this->_redirect('http://google.com');
}
// If not, redirect user to free download page
else
{
$this->_redirect('http://yahoo.com');
}
}
I think you need to check the manual . Foreach function is same wether you use it on zend or any other framework or raw php only.
$referred_users = $this->_helper->user()->getReferredUsers()->toArray();
$referred_users will probably hold an array of emails from the table
user, say:
$referred_users = array("one#email.com", "two#email.com", "three#email.com")
then when you use foreach loop it will iterate through each of the
emails in the array
foreach ($referred_users as $referred_user)
{
// for the first loop $referred_user = one#email.com, for second time $referred_user = two#email.com and goes on
similar_text($email, $referred_user['email'], $similar);
}
Now let us discuss your logic here:
// If yes, Pop up message or redirect to some page
if ($similar < 97)
{
$this->_redirect('http://google.com');
}
// If not, redirect user to free download page
else
{
$this->_redirect('http://yahoo.com');
}
Until and unless the last element in the array $referred_users is exactly equal to your $email
i.e. $email = "three#email.com"
you will always be given result for $similar less than 97% which means you will be redirected to google.
Which I assume you are not trying to do and probably not familiar with foreach function which is why you are not getting the expected result.
Assuming you are trying to do something like, check for the emails in the array if any of the email in the array matches (if array is from table check if the email entered from param is equal to any of the emails in the table) then redirect to somewhere or show some message else carry on. Solution below might be helpful to you.
$similarText = false;
foreach ($referred_users as $referred_user)
{
// for the first loop $referred_user = one#email.com, for second time $referred_user = two#email.com and goes on
similar_text($email, $referred_user['email'], $similar);
if ($similar > 97) {
$similarText = true;
break;
}
}
// If yes, Pop up message or redirect to some page
if ($similarText)
{
$this->_redirect('http://google.com');
}
// If not, redirect user to free download page
else
{
$this->_redirect('http://yahoo.com');
}
Hope you got the idea. But please do check the manual before posting a question in the future.

Creating a history list, preventing multiples

Im creating a website and one of the features is on the side it will show the user the pages they've visited since they got to the website, and they can click any of those names and get it to take them back to that page. I have it working, however when they click back to a certain page if they click through them again it writes out the repeat pages. for instance if say we have 10 pages, main01 to main10. The user gets to page main05, and decides he wants to go back to main03, he click main03 on his history list and goes there just fine, decides he wants to keep going and clicks "continue" this brings him to page main04, which is fine. But the history list becomes:
main01
main02
main03
main04
main05
main03
main04
so what I've tried to do is create a method that checks to see if the page visited has already been added to the array, if it has been then it should just echo nothing. if it hasnt then it echos the correct link. but whenever I try it now it just displays the last page you visited, and overwrites that every time you change pages. Here is my code:
if($_POST['visited']){
$_SESSION['visitedpages'][$_SESSION['i']] = $_POST['visited'];
$_SESSION['i']++;
echo "<pre>";
print_r($_SESSION['visitedpages']);
echo "</pre>";
}
if($_SESSION['visitedpages']){
$a_length = count($_SESSION['visitedpages']);
for($x = 0; $x < $a_length; $x++){
$name = $_SESSION['visitedpages'][$x];
$exists = checkifexists($name, $a_length);
if(!$exists){
echo "$name<br />";
}
else{
echo "";
}
}
}
function checkifexists($name, $a_length){
for($z = 0; $z < $a_length;$z++){
$existingname = $_SESSION['visitedpages'][$z-1];
if($name === $existingname) {
return true;
}
}
return false;
}
how can I get this working correctly? Any help would be appreciated.
EDIT: Actually it looks like I got it working by checking if it exists when its being written to the array, rather than when its being written as a link. However now whenever I click the link to visit the page (for instance main03 from main05) it goes to main03 but the history list doesn't display, any input on this?
EDIT2: So I changed it, using in_array, per your suggestion, and its displaying properly but its still listing duplicates. here is the code Im using:
if(in_array($_POSTED['visited'],$_SESSION['visitedpages'])){
echo "";
}
else{
$_SESSION['visitedpages'][$_SESSION['i']] = $_POST['visited'];
$_SESSION['i']++;
echo "<pre>";
print_r($_SESSION['visitedpages']);
echo "</pre>";
$arrayinit = true;
}
and now the array looks like this whenever I visit previous pages:
Array
(
[0] => main01
[1] => main02
[2] => main03
[3] => main04
[4] => main03
)
You need to check your checkifexists function.
You're checking to see if this page has already been mentioned; if it has, then return true. But what you're doing is going through the whole of $_SESSION['visitedpages'] to see if a page is in there, and of course it is.
Try calling it with:
$exists = checkifexists($name, $x - 1);
Then you'll just check elements earlier in the array to see if they're duplicates.
For what it's worth, you might be able to do this more efficiently with in_array

Losing a session variable between one page with codeigniter session library

In my code i am trying to store a variable between two pages but i either get a string return "images" or 0... or nothing- tried casting it.. echoing in on one page works and displays correct number but as soon as you click through the view to the next page- its lost- i tried turning on cs_sessions in the db and made no difference
<?php
public function carconfirm($car_id = '')
{
if(empty($car_id))
{
redirect('welcome');
}
$this->load->model('mcars');
$car = $this->mcars->getCar($car_id);
$data['car'] = $car->row_array();
$car_id = (int) $car_id;
$this->session->set_userdata('flappy', $car_id);
echo $car_id;
//insert details
//display details
$this->load->view('phps/carconfirm',$data);
}
function confirm()
{
//get vars
$time_slot = $this->session->userdata('slot');
$person_id = $this->session->userdata('person_id');
$car_id = $this->session->userdata('flappy');
$insert_array = array( 'slot'=> $time_slot ,
'car'=> $car_id,
'person_id'=> $person_id
);
print_r($insert_array);
$this->load->model('mbooking');
$result = $this->mbooking->addbooking($insert_array);
if($result)
{
redirect('welcome/options');
}
}
?>
the variable I'm losing is flappy- i changed the name to see if that was the problem
Finally, I fixed this. Using this answer in SO too : codeigniter setting session variable with a variable not working, I scan my js/css for missing resources. Turn out that, my thickbox.js refer to loadingAnimation.gif in, yes, images folder. That's where the images come. Having fix the missing file, the sesion variabel working just fine.
Not sure, why CI replace (maybe) last added session variabel using this, but maybe it's because CI is not using $_SESSION global variabel. CMIIW. I use this article as a hint : http://outraider.com/frameworks/why-your-session-variables-fail-in-codeigniter-how-to-fix-them/

How do I use cookies to store users' recent site history(PHP)?

I decided to make a recent view box that allows users to see what links they clicked on before. Whenever they click on a posting, the posting's id gets stored in a cookie and displays it in the recent view box.
In my ad.php, I have a definerecentview function that stores the posting's id (so I can call it later when trying to get the posting's information such as title, price from the database) in a cookie. How do I create a cookie array for this?
**EXAMPLE:** user clicks on ad.php?posting_id='200'
//this is in the ad.php
function definerecentview()
{
$posting_id=$_GET['posting_id'];
//this adds 30 days to the current time
$Month = 2592000 + time();
$i=1;
if (isset($posting_id)){
//lost here
for($i=1,$i< ???,$i++){
setcookie("recentviewitem[$i]", $posting_id, $Month);
}
}
}
function displayrecentviews()
{
echo "<div class='recentviews'>";
echo "Recent Views";
if (isset($_COOKIE['recentviewitem']))
{
foreach ($_COOKIE['recentviewitem'] as $name => $value)
{
echo "$name : $value <br />\n"; //right now just shows the posting_id
}
}
echo "</div>";
}
How do I use a for loop or foreach loop to make it that whenever a user clicks on an ad, it makes an array in the cookie? So it would be like..
1. clicks on ad.php?posting_id=200 --- setcookie("recentviewitem[1]",200,$month);
2. clicks on ad.php?posting_id=201 --- setcookie("recentviewitem[2]",201,$month);
3. clicks on ad.php?posting_id=202 --- setcookie("recentviewitem[3]",202,$month);
Then in the displayrecentitem function, I just echo however many cookies were set?
I'm just totally lost in creating a for loop that sets the cookies. any help would be appreciated
Don't set multiple cookies - set one that contains an array (serialized). When you append to the array, read in the existing cookie first, add the data, then overwrite it.
// define the new value to add to the cookie
$ad_name = 'name of advert viewed';
// if the cookie exists, read it and unserialize it. If not, create a blank array
if(array_key_exists('recentviews', $_COOKIE)) {
$cookie = $_COOKIE['recentviews'];
$cookie = unserialize($cookie);
} else {
$cookie = array();
}
// add the value to the array and serialize
$cookie[] = $ad_name;
$cookie = serialize($cookie);
// save the cookie
setcookie('recentviews', $cookie, time()+3600);
You should not be creating one cookie for each recent search, instead use only one cookie. Try following this ideas:
Each value in the cookie must be
separated from the other with an
unique separator, you can use . ,
; or |. E.g: 200,201,202
When
retrieving the data from the cookie,
if it exists, use
explode(',',CookieName);, so you'll
end up with an array of IDs.
When adding
data to the cookie you could do,
again, explode(',',CookieName); to
create an array of IDs, then check if the
new ID is not in the array using
in_array(); and then add the value
to the array using array_push();.
Then implode the array using
implode(',',myString); and write
myString to the cookie.
That's pretty much it.

Categories