首页 > 解决方案 > 如何在 CodeIgniter 中创建音频验证码?

问题描述

如何使用 CodeIgniter 中的验证码功能创建音频验证码?

我只是希望它是一个数字验证码。

$config = array(
    'img_path' => './captchas/',
    'img_url' => './captchas/',
    'font_path' => './fonts/tahoma.ttf',
    'img_width' => 96,
    'img_height' => 22,
    'expiration' => 1,
    'word_length' => 5,
    'font_size' => 11,
    'img_id' => 'captcha_image',
    'img_alt' => 'captcha',
    'img_class' => '',
    'img_role' => '',
    'pool' => '0123456789', /* only numeric captcha */
    'colors' => array(
        'background' => array(255, 255, 255),
        'border' => array(255, 255, 255),
        'text' => array(140, 140, 140),
        'grid' => array(170, 170, 170)
    )
);

标签: phphtmlcodeignitercaptcha

解决方案


首先,制作一个文件夹。例如“音频”

然后用您自己的声音创建一个 mp3 文件(或其他格式)。您可以录制您的声音(慢慢地说 0-9)并使用在线软件修剪您的 mp3 文件。然后根据内容重命名新的修剪文件。

0.mp3, 1.mp3, 2.mp3, ..., 8.mp3, 9.mp3

您也可以使用这样的在线语音转文本软件:https ://ttsmp3.com并创建 0-9 mp3 文件。

将您的 mp3 文件(10 个文件)复制到“音频”文件夹。

然后,为语音验证码文件创建一个文件夹。例如“语音验证码”

/* your config array */
$config = array(
    'img_path' => './captchas/',
    'img_url' => './captchas/',
    'font_path' => './fonts/tahoma.ttf',
    'img_width' => 96,
    'img_height' => 22,
    'expiration' => 1,
    'word_length' => 5,
    'font_size' => 11,
    'img_id' => 'captcha_image',
    'img_alt' => 'captcha',
    'img_class' => '',
    'img_role' => '',
    'pool' => '0123456789', /* only numeric captcha */
    'colors' => array(
        'background' => array(255, 255, 255),
        'border' => array(255, 255, 255),
        'text' => array(140, 140, 140),
        'grid' => array(170, 170, 170)
    )
);
/* My added code begins here */
/* create captcha */
$cap = create_captcha($config);
/* new file name */
$file = './Voice-Captcha/' . $cap['filename'] . '.mp3';
/* open a voice file as writable */
$voice = fopen($file, 'a+');
/* split captcha word */
for ($i = 0; $i < $config['word_length']; $i++) {
    /* get audio file name base on splitted captcha word */
    $audio_file = './Audio/' . mb_substr($cap['word'], $i, 1) . '.mp3';
    /* open audio file as readonly */
    $audio = fopen($audio_file, 'r');
    /* read audio data */
    $data = fread($audio, filesize($audio_file));
    /* write audio data to the end of the voice file (append data to prev. data) */
    fwrite($voice, $data);
    /* close audio file */
    fclose($audio);
}
/* close voice file */
fclose($voice);
/* data */
$data['image'] = $cap['image'];
$data['voice'] = '<audio src="' . $file . '" controls></audio>';
/* load view page */
$this->load->view('My-Page', $data);

并查看文件,例如“我的页面”是:

<?php echo $image; ?>
<?php echo $voice; ?>

请记住,如果您想删除旧的语音验证码文件,请在“captcha_helper”中找到这一行:

@unlink($img_path.$filename);

并在其后添加以下代码:

@unlink('./Voice-Captcha/'.$filename.'.mp3');

注意:当您录制自己的声音时,您可以为您的声音添加音频效果或使用几个人的声音创建不同的文件。这些方法增强了安全性,使机器人更难检测声音。


推荐阅读