Help with Session If Else

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
donny
Forum Contributor
Posts: 179
Joined: Mon Aug 11, 2014 11:18 am

Help with Session If Else

Post by donny »

Hello,

I am trying to make a code that will tell me if the user has a order number already assigned in a session.
If he does not have one assigned already, then one will be made for him.

Code: Select all

session_start();
if (isset($_SESSION['ordernum'])) {
    $ordernumber = $_SESSION['ordernum'];
} else {
$ordernumberpre2 = rand(1, 9);
$ordernumberpre = rand(0001, 9999);
$ordernumbercheck = strlen($ordernumberpre);
if ($ordernumbercheck == '4') {
    $ordernumber = $ordernumberpre;
} else if ($ordernumbercheck == '3') {
$ordernumber = $ordernumberpre . $ordernumberpre2;
$_SESSION['ordernum'] = $ordernumber;
}
}
the whole order number mess is basically creating a random 4 digit number, when i use rand() it'll sometimes generate 3 digit numbers for some reason. any help with that will also be great.

thank you
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Help with Session If Else

Post by Celauran »

You're asking for numbers between 1 and 9999. Some of those are going to contain fewer than 4 digits. Either increase the lower bound to 1000, or left pad the number with 0s using str_pad.

Code: Select all

php > echo str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT) . "\n";
0509
php > echo str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT) . "\n";
0770
donny
Forum Contributor
Posts: 179
Joined: Mon Aug 11, 2014 11:18 am

Re: Help with Session If Else

Post by donny »

thank you.. i didn't have register globals on thats why my sessions weren't working

thank you
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Help with Session If Else

Post by Celauran »

Uh... register_globals has been removed from PHP as of 5.4. You really shouldn't be using that and you can use sessions fine without it.
Post Reply