5

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.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Slacks.
  • 199
  • 1
  • 15

1 Answers1

3

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:

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141