stack stack - 5 months ago 15
PHP Question

How can I devote separated session for different pages?

I have following script which generates a captcha:

// captcha.php
session_start();
$captcha_token='';
for($i=1; $i<=5; $i++){$captcha_token .= rand(0,9).' ';}
$_SESSION['captcha'] = str_replace(" ","",$captcha_token);

$im = imagecreatetruecolor(110, 34);
$red = imagecolorallocate($im, 245, 245, 245);
imagefill($im, 0, 0, $red);
$text_color = imagecolorallocate($im, 80, 80, 80);
imagestring($im, 8, 15, 9, $captcha_token, $text_color);
header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);


Also I have multiple pages which need a captcha. I use
captcha.php
for all of them. Something like this:

// contact.php
<input name="captcha" type="text" />
<img src="captcha.php" />

// resend_password.php
<input name="captcha" type="text" />
<img src="captcha.php" />

// multiple_wrong_login.php
<input name="captcha" type="text" />
<img src="captcha.php" />


All fine. Just as you see there is just one session
$_SESSION['captcha']
for all scripts. And when I open
contact.php
and immediately after that
resend_password.php
, then the captcha in the
contact.php
will be invalid. How can I fix it? I mean how can I make a separated captcha for different pages?

Answer

here is my suggestion:

parse a variable to the captcha script like so:

<img  src="captcha.php?page=resend_password" />

then in the script:

$_SESSION['captcha'][$_GET['page']] = str_replace(" ","",$captcha_token);