PHP make a variable have permanent value - php

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

Related

How do you use session variables in wordpress?

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.

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

PHP random link without repetitions

My PHP is poor, but I'm trying my best to improve!!
I'm attempting to code a really simple php script that loads a random html page from a text file list.
Once people have viewed the html page, they link back to the random.php file and it loads another page... this can continue on forever.
I'm using a text file list as I'll regularly be adding more pages. My issue is there is no where in my code to prevent repeat visits!! Right now I only have about 8 links, and on more than one occasion I've had the same link 'randomly' come up 3 times in a row :( Hoping there is something simple I can add to this to prevent repetitions, and if all links have been viewed, then it resets. Many Thanks :)
<body>
<?php
$urlist=file("randomlinks.txt");
$nl=count($urlist);
$np=rand(0,$nl-1);
$url=trim($urlist[$np]);
header("Location: $url");
exit;
?>
</body>
Since the user does not know in what order the links are in the text file, if you were to read said links in sequence they would seem "random" (and you can shuffle them when first creating the file).
So you can:
save in session the index of the last link seen
link the link index to system time. This does not prevent repetitions, but guarantees that no two links come out equal, unless you hit 'refresh' after exactly the right amount of time.
Method 1:
$urlist=file("randomlinks.txt");
$nl=count($urlist);
session_start();
if (!isset($_SESSION['link'])) // If link is not in session
$_SESSION['link'] = 0; // Start from 0 (the first)
$np = $_SESSION['link']++; // Next time will use next
$_SESSION['link'] %= $nl; // Start over if nl exceeded
$url=trim($urlist[$np]);
Header("Location: $url");
Method 2:
...
$nl=count($urlist);
$np = time() % $nl; // Get number of seconds since the Epoch,
// extract modulo $nl obtaining a number that
// cycles between 0 and $nl-1, every $nl seconds
$url=trim($urlist[$np]);
Header("Location: $url");
Another method would be to remember the last N links seen - but for this, you need a session variable - so as not to get them again too soon.
session_start();
if (!isset($_SESSION['urlist'])) // Do we know the user?
$_SESSION['urlist'] = array(); // No, start with empty list
if (empty($_SESSION['urlist'])) // Is the list empty?
{
$_SESSION['urlist'] = file("randomlinks.txt"); // Fill it.
$safe = array_pop($_SESSION['urlist']);
shuffle($_SESSION['urlist']); // Shuffle the list
array_push($_SESSION['urlist'], $safe);
}
$url = trim(array_pop($_SESSION['urlist']));
If you have five URLS 1, 2, 3, 4 and 5, you might get:
1 5 3 4 2 1 4 2 5 3 1 2 3 5 4 1 4 3 2 5 1 4 ...
...the list is N-1 random :-), all links appear with equal frequency, and the same link may reappear at most at a 2-remove, like the "4" above (...4 1 4...); if it does, you'll never see it again for at least $nl visits.
ALSO
You should not use Header() from within a <BODY> tag. Remove <BODY> altogether.
You don't need to use exit() if you are at the natural end of the script: the script will exit by itself.
The simplest way I can think of would be to use a cookie.
The Internet is full of tutorials such as the following:
http://www.w3schools.com/php/php_cookies.asp
For example:
<?php
if (isset($_COOKIE["vistList"]))
$visited = split(","$_COOKIE["visitList"]);
foreach ($visited as &$value) {
if ($value == /* new site url */) {
//Find a new one
}
}
else
$expire=time()+60*60*24*30;
setcookie("vistList", "List-of-visited-URLs, separated-by-commas", $expire);
?>
I have not had a chance to test this code, but hopefully it can give you ideas.
As noted in the comments, the same thing could be accomplished using php sessions:
<?php
session_start();
if (isset($_SESSION["vistList"]))
$visited = split(","$_SESSION["visitList"]);
foreach ($visited as &$value) {
if ($value == /* new site url */) {
//Find a new one
}
}
else
$_SESSION['vistList']=/* new site URL */
?>
I would use PHP sessions to do this. Take a look at this example.
Store an array of available pages in a session variable. Every time you get a page, you remove that page from the array. When the array is empty, you reset it again from your original source.
Here's what your code might look like:
session_start();
if (empty($_SESSION["pages"]))
$_SESSION["pages"] = file("randomlinks.txt");
$nl = count($_SESSION["pages"]);
$np = mt_rand(0, $nl-1);
// get the page, remove it from the array, and shift all higher elements down:
list($url) = array_splice($_SESSION["pages"], $page, 1);
die(header("Location: $url"));

looping through url

I want to do a loop, normally it is done with while do for etc but when the process is big I came up with a solution to refresh the page by echoing a javascript to refresh the page for the next loop.
for example:
The page is http://localhost/index.php --> this preforms the first iteration with $i=1;
at the end of the script it will be redirected to http://localhost/index.php?i=$i++
if (!$_GET['i']){
$i = 1;
}else{
$i = $_GET['i'];
}
if ($i<500){
// proceed with $i = $_GET['i']
//then redirect to http://localhost/index.php?i=$i++
}else{
echo "done";
}
Now, consider a situation that the imput parameters come from a FORM to this script. (i.e. $parameter1 , $parameter2, $parameter3)
Then I have to pass them every time to new url (next iteration).
At normal work I can pass them as GET variable to new url but how can I pass them if I don't want the user be able to see the value of parameters in url?
At normal work I can pass them as GET variable to new url but how can I pass them if I don't want the user be able to see the value of parameters in url?
You can not with the bare redirect, but if you're talking about a specific user, you can do so by assigning those parameters as session variables Docs and then passing the session id as an additional parameter (or trust the user has cookies enabled).
function do_redirect($i, Array $parameters)
{
$i = (int) $i;
$parameters['i'] = $i; // save to session as well
$_SESSION['parameters'] = $parameters;
// redirect to http://localhost/index.php?i=$i&SID
}
if (is_form_request())
{
$parameters = get_form_parameters();
do_redirect(1, $parameters);
}
elseif (is_redirect_loop_request())
{
$parameters = $_SESSION['parameters'];
$i = $parameters['i'];
if ($i < 500)
{
do_redirect($i++, $parameters);
} else {
echo "done.";
}
}
Not to be rude, but both answers above are quite prone to security issues (but the session solution is the best one). As for the 'encryption' solution of #itamar: that's not exactly encryption... This is called 'Caesar cypher' (http://en.wikipedia.org/wiki/Caesar_cipher), which is indeed as safe as a paper nuclear bunker...
It can be much easier and safe as can be; do not save the iteration in the session, but in the database. For the next request, the only thing you have to do is get the iterator from the database and go on with whatever you want to do. Sessions can be stolen, meaning someone could let you iterate from, say, $i=10 a thousand times. It cannot be done when the iterator is stored in a secure database.

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