PHP 验证码 - 某些 Web 浏览器不显示文本但显示背景

PHP Captcha - Text Not Showing But Background to Certain Web Browser

我遇到 PHP 验证码不向某些网络浏览器显示文本。

我在我的桌面上使用 Firefox 和 IE 尝试过,它能够工作。当我像其他方桌面或移动设备一样尝试时,它没有显示验证码中的文本。

一开始以为是cPanel中没有字体,导致字体显示不出来。因此,我上传了两种不同的字体并尝试。

但是出现了同样的问题

这就是我的代码和文件管理器的样子。如果您需要更多详细信息,请告诉我。

session_start();
$captcha_answer = $_SESSION['captcha_answer'];
$handle = ImageCreate (100, 40) or die ("Cannot Create image"); 
$bg_color = ImageColorAllocate ($handle, 176, 26, 72); //green
$font_color = ImageColorAllocate ($handle, 255, 255, 255);
$font = 'NotoSans.ttf';

imagettftext($handle, 20, 0, 10, 20, $bg_color, $font, $captcha_answer);
imagettftext($handle, 20, 7, 13, 32, $font_color, $font, $captcha_answer);

ImagePng($handle);

cPanel File Manager - Click Here to View

已找到更新解决方案

这是因为 HTTP > HTTPS 问题。

Aside from the technical aspects of how Transport Layer Security works, the other facet of securely exchanging data lies in how well we apply that security. For example, if we allow a user to submit an application’s login form data over HTTP we must then accept that an MitM is completely capable of intercepting that data and recording the user’s login data for future use. If we allow pages loaded over HTTPS to, in turn, load non-HTTPS resources then we must accept that a MitM has a vehicle with which to inject Cross-Site Scripting attacks to turn the user’s browser into a pre-programmed weapon that will operate over the browser’s HTTPS connection tranparently.

来源:http://phpsecurity.readthedocs.org/en/latest/Transport-Layer-Security-(HTTPS-SSL-and-TLS).html

尝试为 png 图像设置正确的 header:

session_start();
$captcha_answer = $_SESSION['captcha_answer'];
$handle = ImageCreate (100, 40) or die ("Cannot Create image"); 
$bg_color = ImageColorAllocate ($handle, 176, 26, 72); //green
$font_color = ImageColorAllocate ($handle, 255, 255, 255);
$font = 'NotoSans.ttf';

imagettftext($handle, 20, 0, 10, 20, $bg_color, $font, $captcha_answer);
imagettftext($handle, 20, 7, 13, 32, $font_color, $font, $captcha_answer);

header('Content-Type: image/png');
ImagePng($handle); 

此外,我建议设置 headers 以便浏览器不缓存图像,以防图像始终动态生成。请参阅 this 关于如何实现该目标的回答。

@session_start();
$_SESSION['captcha_answer'] = "hello";
$captcha_answer = $_SESSION['captcha_answer'];
$handle = ImageCreate (100, 40) or die ("Cannot Create image"); 
$bg_color = ImageColorAllocate ($handle, 176, 26, 72); //green
$font_color = ImageColorAllocate ($handle, 255, 255, 255);
$font = 'font/monofont.ttf';  // your font path goes here....

header('Content-Type: image/png');
imagettftext($handle, 20, 0, 10, 20, $bg_color, $font, $captcha_answer);
imagettftext($handle, 20, 7, 13, 32, $font_color, $font, $captcha_answer);

ImagePng($handle);