Slacks.
Slacks.

Reputation: 199

Generating a random number to be used as same in subsequent pages

Currently I am generating a random number for my advertising landing page to make up for MB being used and it's working nicely.

But I am wondering if it's possible for me to somehow get the same number that is being generated each time with <?php echo(rand(10,20)); ?> so I can use it in multiple locations.

Upvotes: 5

Views: 88

Answers (1)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

You can achieve this using sessions.

First you need to start a session, assign a session array to the random function, then a variable from that session array.

<?php 
session_start(); 
$_SESSION['var'] = rand(10,20); 

$var = $_SESSION['var']; 

Then you can use that in subsequent pages, just as long as you start the session in those pages also.

Reference:

Example:

File 1

<?php 
session_start(); 
$_SESSION['var'] = rand(10,20); 

echo $var = $_SESSION['var']; 

File 2

<?php 
session_start(); 

echo $var = $_SESSION['var']; 

Sidenote:

Make sure there isn't anything above that, as it may trigger a headers sent notice.

If you do get one, visit the following page on Stack:

Upvotes: 3

Related Questions