将php验证码实现到laravel框架中

时间:2015-03-08 16:17:30

标签: php laravel captcha

我试图让这个验证码在laravel框架中运行。我希望它能够与一个联系人页面一起使用,但我不知道如何将php部分实现到laravel框架中,因为我试图将它放在控制器中的post contact us函数中,但它会破坏我的程序

视图中的Html

<img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" />
 <input type="text" name="captcha_code" size="10" maxlength="6" />

 <a href="#" onclick="document.getElementById('captcha').src = '/securimage/securimage_show.php?' + Math.random(); return false">[ DifferentImage ]</a>

这个代码我试图进入控制器:

include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';

$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
  // the code was incorrect
  // you should handle the error so that the form processor doesn't continue

  // or you can use the following code if there is no validation or you do not know how                   
  echo "The security code entered was incorrect.<br /><br />";
  echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
  exit;
}

以下是:文档https://www.phpcaptcha.org/documentation/quickstart-guide/

1 个答案:

答案 0 :(得分:2)

我假设您在服务器上运行了securimage_test.php并且测试通过了。以下是我为使其发挥作用所做的一切。

"require": { ... },

中将此行添加到您应用的composer.json中
    "dapphp/securimage": "~3.5",

运行composer update安装securimage包并将其类添加到自动加载中。

对于图像和输入,我将其添加到我的表单中:

<img id="captcha" style="width: 241px; height: 80px;" src="/captcha" alt="CAPTCHA Image" />
<input class="form-control" type="text" name="captcha_code" size="10" maxlength="6" />
<a href="#" onclick="document.getElementById('captcha').src = '/captcha?' + Math.random(); return false">[Generate a new image]</a>

添加&#39; /验证码&#39;或者您想要用作路径文件的验证码图像的任何其他URL,以指向作为securimage_show.php

中函数副本的函数 routes.php中的

Route::get('/captcha', 'HomeController@getCaptcha');

就我而言,它位于HomeController.php

public
function getCaptcha()
{
    $img = new Securimage();

    // set namespace if supplied to script via HTTP GET
    if (!empty($_GET['namespace'])) $img->setNamespace($_GET['namespace']);

    $img->show();  // outputs the image and content headers to the browser
    // alternate use:
    // $img->show('/path/to/background_image.jpg');
}

然后在post方法中,无论您在何处验证表单,都要为验证码添加验证:

    $image = new Securimage();
    if ($image->check(Input::get('captcha_code')) !== true)
    {
        // add however you handle feedback to the user here
        $errors = new MessageBag();
        $errors->add('captcha_code', 'Text you entered does not match');
        return Redirect::back()
            ->with('errors', $errors)
            ->withInput(Input::only('email', 'name'));
    }
    // text matches, go on processing