How do you use session variables in wordpress? - php

I have the following plugin: http://wordpress.org/support/plugin/wp-session-manager
I cannot work out how to use the session variables in WordPress. From what I understand by reading, this is how it should be used:
I have the following on page one (page 1):
global $wp_session;
$wp_session['loggedIn'] = 15;
echo $wp_session['loggedIn'];
On the first page, the session variable is working but on the second page, the session variable is not working.
Can anyone suggest me where I am going wrong?
Thanks.

Replace:
global $wp_session;
With:
$wp_session = WP_Session::get_instance();
Make sure you add $wp_session = WP_Session::get_instance(); before you try to echo the variable on page 2.

Add below code in function.php file
function register_my_session(){
if( ! session_id() ) {
session_start();
}
}
add_action('init', 'register_my_session');
After that you can store value in session variable like
$_SESSION['something'] = $xyz

Introducing WP_Session:
Example :
global $wp_session;
$wp_session['user_name'] = 'User Name'; // A string
$wp_session['user_contact'] = array( 'email' => 'user#name.com' );// An array
$wp_session['user_obj'] = new WP_User( 1 ); // An object
Wordpress session functions:
wp_session_cache_expire() – get the session expiration time
wp_session_commit() – write session data out to the transient
wp_session_decode() – load data into the session from a serialized string
wp_session_encode() – write session data out to a serialized string
wp_session_regenerate_id() – change the ID of the current session to a new, random one
wp_session_start() – start the session and load data based on the user’s cookie
wp_session_status() – check the status of the current session
wp_session_unset() – clear out all variables in the current session
wp_session_write_close() – write session data and end session.

Related

PHP make a variable have permanent value

I use a variable, value of which is a random string. Every time I refresh the page, that string changes. All good but I need to echo also the random string that was also generated before the new refresh, in other words store that string into a permanent let's say variable. Example: 12345 is generated, reload, abcde is generated but I want 12345 to be echoed as well... How can I do this? Thanks
You can put that variable value in the php SESSION
<?php session_start();
$str = "";
if(!isset($_SESSION['var1']) || empty($_SESSION['var1']))
{
$str = ... // random a string
$_SESSION['var1'] = str; // save in session
}
else $str = $_SESSION['var1']; // get the value back from session
?>
Also on the logout time, instead of deleting the whole session global variable, you should delete the specific session.
session_unset($_SESSION['specific_session']);

Preserving $_POST variables when paginating

I have a simple list of orders which a user can filter by status (open,dispatched,closed). The filter dropdown triggers a post to the server and sends the filter value through. Orders are listed out 10 to a page with pagination links for any results greater than 10. Problem is when I click the pagination links to view the next page of results the filter value in the post is lost.
public function filter_orders() {
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$filter = $this->input->post('order_status_filter');
$config = array();
$config["base_url"] = base_url() . "control/orders/filter_orders";
$config["per_page"] = 10;
$config['next_link'] = 'Next';
$config["uri_segment"] = 4;
$config['total_rows'] = $this->model_order->get_all_orders_count($this->input->post('order_status_filter'));
}
How can I make the pagination and filter work together. I've thought about injecting a query string in to the pagination links but it doesn't seem like a great solution.
The answer is very simple, use $_GET. You can also use URI segments.
i.e, index.php/cars/list/5/name-asc/price-desc'
The main reason you'll want to use $_GET is so you can link other users so they see the same result set you see. I'm sure users of your web app will want this functionality if you can imagine them linking stuff to each other.
That said, it would be ok to ALSO store the filters in the session so that if the user navigates away from the result set and then goes back, everything isn't reset.
Your best bet is to start a session and store the POST data in the session. In places in your code where you check to see if the user has sent POST data, you can check for session data (if POST is empty).
In other words, check for POST data (as you already do). If you got POST data, store it in the session. If a page has no POST data, check to see if you have session data. If you do, proceed as if it was POSTed. If you have both, overwrite the session with POST. You'll want to use new data your user sent you to overwrite older data they previously sent.
You either put everything in $_GET or if the data is sensible, put it in $_SESSION. Then it travels between pages.
In your case there seem to be no reason to put your filter data anywhere else than in $_GET.
A query string does seem the best solution. You could store it in the session or in cookies as well, but it makes sense to also store it in the query string.
Store it in cookies or the session if you want to remember the user's choice. Which seems like a friendly solution. It allows the user to keep their settings for a next visit, or for another page.
Store it in the query string, because going to 'page 2' doesn't tell you anything if you don't know about filters, page size or sorting. So if a user wants to bookmark page 2 or send it by e-mail, let them be able to send a complete link that contains this meta information.
Long story short: Store it in both.
maybe its not a right answer but, give it a try
<?php
// example url
$url = "index.php?page=6&filter1=value1&filter2=value2";
// to get the current url
//$url = "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
// change the page to 3 without changing any other values
echo url_change_index( $url, "page", 3 );
// will output "index.php?page=3&filter1=value1&filter2=value2"
// remove page index from url
echo url_change_index( $url, "page" );
// will output "index.php?filter1=value1&filter2=value2"
// the function
function url_change_index( $url, $name = null, $value = null ) {
$query = parse_url( $url, PHP_URL_QUERY );
$filter = str_replace( $query, "", $url );
parse_str( $query, $parsed );
$parsed = ( !isset( $parsed ) || !is_array( $parsed ) ) ? array() : $parsed;
if ( empty( $value ) ) {
unset( $parsed[$name] );
}
else {
$parsed[$name] = $value;
}
return $filter.http_build_query( $parsed );
}
?>

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

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