Page 1 of 1

Help with Session If Else

Posted: Thu Aug 14, 2014 3:38 pm
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

Re: Help with Session If Else

Posted: Thu Aug 14, 2014 3:43 pm
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

Re: Help with Session If Else

Posted: Thu Aug 14, 2014 3:47 pm
by donny
thank you.. i didn't have register globals on thats why my sessions weren't working

thank you

Re: Help with Session If Else

Posted: Thu Aug 14, 2014 4:20 pm
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.