How can the PHP code be modified to ensure that the captcha image displays correctly on all systems and browsers?
The issue of the captcha image not displaying correctly on all systems and browsers can be solved by ensuring that the image is generated with the correct content type and headers. This can be achieved by setting the content type to image/png and sending appropriate headers before outputting the image data.
<?php
// Start the session
session_start();
// Generate a random captcha code
$captcha_code = substr(md5(rand()), 0, 6);
// Store the captcha code in the session
$_SESSION['captcha_code'] = $captcha_code;
// Create a blank image with dimensions 120x30
$captcha_image = imagecreatetruecolor(120, 30);
// Set the background color to white
$bg_color = imagecolorallocate($captcha_image, 255, 255, 255);
imagefill($captcha_image, 0, 0, $bg_color);
// Set the text color to black
$text_color = imagecolorallocate($captcha_image, 0, 0, 0);
// Write the captcha code on the image
imagestring($captcha_image, 5, 10, 5, $captcha_code, $text_color);
// Set the content type and send appropriate headers
header('Content-type: image/png');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0');
header('Pragma: no-cache');
// Output the image
imagepng($captcha_image);
// Free up memory
imagedestroy($captcha_image);
?>
Related Questions
- How can the use of indexes in a MySQL table improve the performance of PHP scripts that involve data comparisons?
- What are the potential advantages of exporting data as CSV for easier processing in PHP?
- What potential pitfalls can arise when using the mysql_query function in PHP for database operations?