CAPTCHA 헬퍼

CAPTCHA 헬퍼 파일에는 CAPTCHA 이미지 생성을 도와주는 함수가 포함되어 있습니다.

헬퍼 로드

이 헬퍼는 다음 코드를 사용하여 로드합니다:

$this->load->helper('captcha');

CAPTCHA 헬퍼 사용

로드되면 다음과 같이 CAPTCHA를 생성할 수 있습니다:

$vals = array(
        'word'          => 'Random word',
        'img_path'      => './captcha/',
        'img_url'       => 'http://example.com/captcha/',
        'font_path'     => './path/to/fonts/texb.ttf',
        'img_width'     => '150',
        'img_height'    => 30,
        'expiration'    => 7200,
        'word_length'   => 8,
        'font_size'     => 16,
        'img_id'        => 'Imageid',
        'pool'          => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',

        // White background and border, black text and red grid
        'colors'        => array(
                'background' => array(255, 255, 255),
                'border' => array(255, 255, 255),
                'text' => array(0, 0, 0),
                'grid' => array(255, 40, 40)
        )
);

$cap = create_captcha($vals);
echo $cap['image'];
  • captcha 함수는 GD 이미지 라이브러리가 필요합니다.

  • 이미지를 디스크에 쓰려면 img_pathimg_url 이 모두 필요합니다. data:image/png;base64 이미지를 만들려면 이 옵션을 생략하면 됩니다.

  • word가 제공되지 않으면 함수는 임의의 ASCII 문자열을 생성합니다. 임의로 선택할 수 있는 자체 단어 라이브러리를 만들 수도 있습니다.

  • TRUE TYPE 폰트 경로를 지정하지 않으면 기본 못생긴 GD 폰트가 사용됩니다.

  • “captcha” 디렉터리는 쓰기 가능해야 합니다.

  • expiration (초 단위)은 이미지가 삭제되기 전에 captcha 폴더에 남아 있는 시간을 나타냅니다. 기본값은 2시간입니다.

  • word_length 기본값은 8, pool 기본값은 ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’입니다.

  • font_size 기본값은 16이며, 기본 GD 폰트는 크기 제한이 있습니다. 더 큰 크기에는 “true type” 폰트를 지정하세요.

  • img_id는 captcha 이미지의 “id”로 설정됩니다.

  • colors 값 중 하나가 없으면 기본값으로 대체됩니다.

데이터베이스 추가

captcha 함수가 제출을 방지하려면 create_captcha()에서 반환된 정보를 데이터베이스에 추가해야 합니다. 사용자가 양식 데이터를 제출하면 데이터가 데이터베이스에 존재하고 만료되지 않았는지 확인해야 합니다.

다음은 테이블 프로토타입입니다:

CREATE TABLE captcha (
        captcha_id bigint(13) unsigned NOT NULL auto_increment,
        captcha_time int(10) unsigned NOT NULL,
        ip_address varchar(45) NOT NULL,
        word varchar(20) NOT NULL,
        PRIMARY KEY `captcha_id` (`captcha_id`),
        KEY `word` (`word`)
);

다음은 데이터베이스를 사용하는 예시입니다. CAPTCHA가 표시되는 페이지에는 다음과 같은 내용이 있습니다:

$this->load->helper('captcha');

$cap = create_captcha($vals);
$data = array(
        'captcha_time'  => $cap['time'],
        'ip_address'    => $this->input->ip_address(),
        'word'          => $cap['word']
);

$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);

echo 'Submit the word you see below:';
echo $cap['image'];
echo '<input type="text" name="captcha" value="" />';

제출을 받는 페이지에는 다음과 같은 내용이 있습니다:

// 먼저 오래된 captcha를 삭제합니다.
$expiration = time() - 7200; // 두 시간 제한
$this->db->where('captcha_time < ', $expiration)
        ->delete('captcha');

// 그런 다음 captcha가 있는지 확인합니다.
$sql = 'SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?';
$binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();

if ($row->count == 0)
{
        echo 'You must submit the word that appears in the image.';
}

사용 가능한 함수

사용 가능한 함수는 다음과 같습니다:

create_captcha($data)
매개변수:
  • $data (array) – CAPTCHA 데이터 배열

반환:

array(‘word’ => $word, ‘time’ => $now, ‘image’ => $img)

반환 형식:

array

CAPTCHA를 생성하기 위한 정보 배열을 입력으로 받아 사양에 따라 이미지를 생성하고 이미지에 대한 연관 데이터 배열을 반환합니다.

array(
        'image' => IMAGE TAG
        'time'  => TIMESTAMP (in microtime)
        'word'  => CAPTCHA WORD
)

image는 실제 이미지 태그입니다:

<img src="data:image/png;base64,RHVtbXkgZXhhbXBsZQ==" width="140" height="50" />

time은 파일 확장자 없이 이미지 이름으로 사용되는 마이크로 타임스탬프입니다. 1139612155.3422와 같은 숫자입니다.

word는 captcha 이미지에 나타나는 단어로, 함수에 제공되지 않으면 임의의 문자열입니다.