monchichi
monchichi

Reputation: 47

PHP Sessions: Generate a variable and save it for session

I am totally new to php sessions. I am not able to get a simple task done. This is what I am trying to do:

well this part works so far. But everytime the user goes on to another page (I have this random image shown on all pages) the script generates a new random image to be shown.

What I want to do now is:

Here is my working code to get a random image without saving it into sessions. If anybody could help me with how the code should look like so it works with sessions would be awesome. Remember: I am a total newby when it comes to sessions.

As you can see I need the variable $img to be stored into a session after it got generated. And the script only to strt again on a new site visit if a user hasnt stored the $img variable in his session.

<?php
function getImagesFromDir($path) {
$images = array();
if ( $img_dir = @opendir($path) ) {
    while ( false !== ($img_file = readdir($img_dir)) ) {
        // checks for gif, jpg, png
        if ( preg_match("/(\.gif|\.jpg|\.png)$/", $img_file) ) {
            $images[] = $img_file;
        }
    }
    closedir($img_dir);
}
return $images;
}

function getRandomFromArray($ar) {
mt_srand( (double)microtime() * 1000000 ); // php 4.2+ not needed
$num = array_rand($ar);
return $ar[$num];
}


$root = '';
// use if specifying path from root
//$root = $_SERVER['DOCUMENT_ROOT'];

$path = 'images/';


// Obtain list of images from directory 
$imgList = getImagesFromDir($root . $path);
$img = getRandomFromArray($imgList);
?> 

<img src="/<?php echo $path . $img ?>" alt="image" />

Upvotes: 3

Views: 306

Answers (2)

Tzar
Tzar

Reputation: 1829

You'll need to add this at the top of every page to get your image:

session_start();
if(isset($_SESSION['UserImg'])){
   $img = $_SESSION['UserImg'];
}
else {
    $img = getRandomFromArray($imgList);
    $_SESSION['UserImg'] = $img;
}

This should work out!

Upvotes: 3

Alesfatalis
Alesfatalis

Reputation: 777

on top of each page call:

session_start();

To safe variable in session for example:

$_SESSION['imageid'] = $ID

To get the variable back:

$imageid = $_SESSION['imageid']

Upvotes: 0

Related Questions