Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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.

like image 850
Slacks. Avatar asked Oct 18 '22 20:10

Slacks.


1 Answers

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:

  • http://php.net/manual/en/session.examples.basic.php

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:

  • How to fix "Headers already sent" error in PHP
like image 113
Funk Forty Niner Avatar answered Oct 21 '22 16:10

Funk Forty Niner