I'm having some trouble in creating a simple captcha code. I have a button where the captcha appears and if the user clicks on it it's supposed to show another captcha. The problem is that nothing happens. The PHP generates the captcha but the onclick event seems that's not triggered. Any suggestion?
My PHP Code:
$random_alpha = md5(rand());
$captcha_code = substr($random_alpha, 0, 6);
$_SESSION['CAPTCHA_CODE'] = $captcha_code;
$im = @imagecreatetruecolor(70,30);
imagesavealpha($im, true);
imagealphablending($im, false);
$white = imagecolorallocatealpha($im, 255, 255, 255, 127);
imagefill($im, 0, 0, $white);
$lime = imagecolorallocate($im, 204, 255, 51);
$captcha_text_color = imagecolorallocate($im, 0, 0, 0);
imagestring($im, 5, 5, 5, $captcha_code, $captcha_text_color);
header("Content-type: image/png");
imagepng($im);
imagedestroy($im);
My JS:
<script>
function refreshCaptcha() {
event.preventDefault();
$("#captcha_code").attr('src', './controllers/captcha.php');
}
</script>
My HTML:
<button onclick="refreshCaptcha();" class="btn btn-block btn-hero btn-noborder btn-rounded btn-alt-info" id="captcha" name="captcha">
<i class="si si-refresh mr-10"></i><img id="captcha_code" src="../controllers/captcha.php" />
</button>
If I refresh the page manually it creates a new captcha code, so I know it's working. Where is my mistake?
Thanks!
EDIT: I think that could be something related to my session in PHP. I use the following code to generate the session:
$session_name = 'THA_SESSION'; // Set session name
$secure = false;
// Avoid JS to access session info
$httponly = true;
// Force session to use cookies
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ./errno.php");
exit();
}
// Get the cookie params
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Set the session with the name defined above
session_name($session_name);
session_start(); // starts session