簡體   English   中英

PHP:創建一個簡單的驗證碼

[英]PHP: Creating a simple Captcha

我已經創建了一個簡單的驗證碼生成器,但是不會顯示captcha-image:

index.php:

<?php
session_start();
$_SESSION['captcha'] = rand(1000, 9999);
?>

<img src="generator.inc.php" />

generator.inc.php:

<?php
session_start();
header('Content-type: image/jpeg');

$text = $_SESSION['captcha'];

$font_size = 30;
$image_width = 160;
$image_height = 50;

$image = imagecreate($image_width, $image_height);

imagecolorallocate($image, 200, 200, 200);

$font_color = imagecolorallocate($image, 20 , 20 , 20);

imagettftext($image, $font_size, 0, 15, 30, $font_color, 'BYekan.ttf', $text);

imagejpeg($image);
?>

請告訴我我做錯了什么?

PS:

我在Linux上使用Lamp服務器。

可能未安裝GD庫

還要檢查php.ini ,並確保GD行未注釋。

我刪除了腳本中的header函數調用,發現一個錯誤,即您尚未定義$image_height變量。 在腳本中,復制$image_width分配。

我的建議是嘗試兩件事:

我已經閱讀並看到過有人建議放置內容類型header('Content-type: image/jpeg'); 就在imagejpeg($image); 為了證明這一點,這里提供了一篇有關它的文章: http ://php.net/manual/en/function.imagejpeg.php

我的其他建議是對文件進行base64_encode。 如果header('Content-type: image/jpeg'); 產生錯誤提示“ 必須在發送任何實際輸出之前調用header() ”,然后base64_encode允許使用指定的內容類型創建圖像。 刪除標題代碼,然后在imagejpeg($image);時添加以下代碼imagejpeg($image); 叫做。

ob_start();
imagejpeg($image); //your code
$img = ob_get_contents();
ob_end_clean();
echo '<img src="data:image/jpeg;base64,'.base64_encode($img).'" />';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM