Coder Social home page Coder Social logo

captcha's Introduction

Captcha for Laravel 5/6/7/8/9

Build Status Scrutinizer Code Quality Latest Stable Version Latest Unstable Version License Total Downloads

A simple Laravel 5/6 service provider for including the Captcha for Laravel.

for Laravel 4 Captcha for Laravel Laravel 4

Preview

Preview

Installation

The Captcha Service Provider can be installed via Composer by requiring the mews/captcha package and setting the minimum-stability to dev (required for Laravel 5) in your project's composer.json.

{
    "require": {
        "laravel/framework": "5.0.*",
        "mews/captcha": "~2.0"
    },
    "minimum-stability": "stable"
}

or

Require this package with composer:

composer require mews/captcha

Update your packages with composer update or install with composer install.

In Windows, you'll need to include the GD2 DLL php_gd2.dll in php.ini. And you also need include php_fileinfo.dll and php_mbstring.dll to fit the requirements of mews/captcha's dependencies.

Usage

To use the Captcha Service Provider, you must register the provider when bootstrapping your Laravel application. There are essentially two ways to do this.

Find the providers key in config/app.php and register the Captcha Service Provider.

    'providers' => [
        // ...
        'Mews\Captcha\CaptchaServiceProvider',
    ]

for Laravel 5.1+

    'providers' => [
        // ...
        Mews\Captcha\CaptchaServiceProvider::class,
    ]

Find the aliases key in config/app.php.

    'aliases' => [
        // ...
        'Captcha' => 'Mews\Captcha\Facades\Captcha',
    ]

for Laravel 5.1+

    'aliases' => [
        // ...
        'Captcha' => Mews\Captcha\Facades\Captcha::class,
    ]

Configuration

Custom settings:

To use your own settings, publish config.

$ php artisan vendor:publish

config/captcha.php

return [
    'default'   => [
        'length'    => 5,
        'width'     => 120,
        'height'    => 36,
        'quality'   => 90,
        'math'      => true,  //Enable Math Captcha
        'expire'    => 60,    //Captcha expiration
    ],
    // ...
];

Disable validation:

To disable the captcha validation use CAPTCHA_DISABLE environment variable. e.g. .env config:

CAPTCHA_DISABLE=true

Example Usage

Session Mode:

    // [your site path]/Http/routes.php
    Route::any('captcha-test', function() {
        if (request()->getMethod() == 'POST') {
            $rules = ['captcha' => 'required|captcha'];
            $validator = validator()->make(request()->all(), $rules);
            if ($validator->fails()) {
                echo '<p style="color: #ff0000;">Incorrect!</p>';
            } else {
                echo '<p style="color: #00ff30;">Matched :)</p>';
            }
        }
    
        $form = '<form method="post" action="captcha-test">';
        $form .= '<input type="hidden" name="_token" value="' . csrf_token() . '">';
        $form .= '<p>' . captcha_img() . '</p>';
        $form .= '<p><input type="text" name="captcha"></p>';
        $form .= '<p><button type="submit" name="check">Check</button></p>';
        $form .= '</form>';
        return $form;
    });

Stateless Mode:

You get key and img from this url http://localhost/captcha/api/math and verify the captcha using this method:

    //key is the one that you got from json response
    // fix validator
    // $rules = ['captcha' => 'required|captcha_api:'. request('key')];
    $rules = ['captcha' => 'required|captcha_api:'. request('key') . ',math'];
    $validator = validator()->make(request()->all(), $rules);
    if ($validator->fails()) {
        return response()->json([
            'message' => 'invalid captcha',
        ]);

    } else {
        //do the job
    }

Return Image

captcha();

or

Captcha::create();

Return URL

captcha_src();

or

Captcha::src('default');

Return HTML

captcha_img();

or

Captcha::img();

To use different configurations

captcha_img('flat');

Captcha::img('inverse');

etc.

Based on Intervention Image

^_^

Links

captcha's People

Contributors

alisafari avatar assmay avatar eromoe avatar farzinghanbari avatar hutushen222 avatar immeyti avatar inirudi avatar jcanchor avatar jeffwfly avatar jp7anderson avatar jxlwqq avatar khalilst avatar laravel-shift avatar lddsb avatar lin-h avatar marktan93 avatar mauris avatar mewebstudio avatar mohammedelattar avatar mweghorst avatar mwllgr avatar ocalypto avatar saidbakr avatar scrutinizer-auto-fixer avatar sergej-tihonov avatar shahramfdl avatar sineld avatar smartpixelim avatar vinodraut avatar ycrao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

captcha's Issues

disable sensitive on mewebstudio/captcha

I'm trying to disable sensitive on this package of laravel, for disable that i'm using flat configuration and add this key-value for the configuration:

HTML:

<img src="{{Captcha::src('flat')}}" id="register-captcha-image">

Configuration:

'flat'   => [
    'length'    => 6,
    'width'     => 60,
    'height'    => 30,
    'quality'   => 90,
    'lines'     => 6,
    'bgImage'   => false,
    'sensitive' => false,
    'bgColor'   => '#ecf2f4',
    'fontColors'=> ['#2c3e50', '#c0392b', '#16a085', '#c0392b', '#8e44ad', '#303f9f', '#f57c00', '#795548'],
    'contrast'  => -25,
],

I'm expect to disable sensitive after run this command:

php artisan vendor:publish

after run this command i get this message:

Publishing complete for tag []!

Several case sensitivity issues

There seem to be a few issues regarding changing the case sensitivity of the captcha.
First and foremost, in Captcha.php:378:
$store = $this->str->lower($store);
the hash of the correct captcha is converted to lower case. But converting a hash to lower case is meaningless, and you should just remove this line. This conversion to lowercase is done in generate anyway, before it is stored.
However, the condition for this is also wrong. In Captcha.php:375:
if ($this->sensitive)
{
$value = $this->str->lower($value);
$store = $this->str->lower($store);
}
this logic seems to be wanted when the captcha is not regarded case sensitive, which should be when sensitive is set to false, so there's a "!" missing in the condition. The other place this condition is used, it is correct, so it's not a matter of convention.
However, there's a third issue that prevents this feature from working altogether. The configuration is loaded only when create is called, it seems. So the creation of the captcha is done case insensitive. The configuration is not loaded when the captcha is checked, so the "sensitive" option is never loaded. Hence the only reliable method to make the captcha case insensitive is to hardcode it in the captcha class. Either the configuration needs to be loaded at a different point, or whether the captcha is case sensitive should be stored in a session.
Or you could always make the captcha case insensitive. For example the "c" and the "C" and "u" and "U" are sometimes nearly impossible to distinguish, so people using case sensitive on their website should really reconsider this.

Best regards and good luck fixing this.

laravel 5.2 without changes in kernel.php

      // HTTP routing
    //route need in group of web middleware!!!
    $this->app['router']->group(['middleware' => 'web'], function () {
        $this->app['router']->get('captcha/{config?}', '\Mews\Captcha\CaptchaController@getCaptcha');
    });

Issues with Laravel 5.2 - Session

Laravel 5.2 removes important global middleware and introduces middleware groups.

This is great but also brought a "bug" to my app. All captchas were invalid since \Illuminate\Session\Middleware\StartSession::class wasn't used for the captcha image url.

Workarounds:

Add \Illuminate\Session\Middleware\StartSession::class to $middleware in Kernel.php

or

Change line 26 in CaptchaServiceProvider to:

$this->app['router']->get('captcha/{config?}', '\Mews\Captcha\CaptchaController@getCaptcha')->middleware('web');

My question:

Is there any other way to fix this "issue" (if it is one).

Regards,
Andre

Multiple Captcha On One Page

I have one page which has multiple forms, I tried this but it is creating a problem.
I have already use this plugin on whole site and its working fine so i don't want to change the plugin.
Please help me out.

Captcha image not displaying

Hello,

Just trying this for the first time and can't get it to work in my dev environment. The image is just not rendering. After the page loads, the source of the image is: http://localhost/site/public/captcha?454234

When going to the image URL the error the browser throws is: "The image cannot be displayed because it contains errors"

I'm working on a Windows dev environment, already checked to make sure the necessary dlls were installed. Also published my site to a staging Unix environment and still having the same results.

Is this a bug or something I'm missing?

Class captcha does not exist

Hi
Sorry for my bad English.

I install mewebstudio captcha using composer "composer require mews/captcha", run bot "composer update" and "composer install" .

Edit file "config/app.php" (I using laravel 5.1)

 'providers' => [
        // ...
        Mews\Captcha\CaptchaServiceProvider::class,
    ]

'aliases' => [
        // ...
        'Captcha' => Mews\Captcha\Facades\Captcha::class,
    ]

Run command line "php artisan vendor:publish" but it don't genarate file captcha.php in folder config (I must create it by hand).

When I put "{{ captcha_src() }}" in xxx.blade.php then it error
"Class captcha does not exist (View: C:\wamp\www\lar\resources\views\xxx)"

Thanks

session keeps regenerating on every request for 5.2

Newbie to laravel.
While digging into the problem of session()->flash failure, I found the
"for Laravel 5.2+ Add \Illuminate\Session\Middleware\StartSession::class to $middleware in Kernel.php"
is the culprit.
Session files keep regenerating after doing that.

Letters are visible partially

Thanks for this really useful package.
Letters are are generally visible partially and some part are placed out of the canvas. I make reading hard. Also pleas consider adding an option to choose characters set (with this options)

Project Dead

This project seems pretty dead to me, any active forks recommended?

imagettftext(): Could not read font

I got imagettftext(): Could not read font (on image action).
Ive tried to change the permissions on vendor public folder of mews/captcha but no luck.
The assets are there. but for some reason the imagettftext cannot read it?
Thanks in advance.

e2e testing

Hey, any thoughts on how I could handle e2e testing on a site that uses captcha? Is there any back-end hook that would let me pipe the solution into a test runner?

Güncelleme

Merhaba,

Powerpack'e ihtiyaç kalmadığından bir güncelleme yayınlamanız gerekecektir, bu yönde bir çalışmanız var mı?

Teşekkürler.

Route missing?

Isn't there a route missing for simple usage like

Route::get('/captcha/{config?}' ...

why not add a param for session key

i think it's usefull to rename a session
\vendor\mews\captcha\src\Captcha.php
line 277 $this->session->put('captcha', $this->hasher->make($bag));

What should I implement into the view

Hi,
I just followed your guide to install the captcha bundle for laravel 4. As you guess I am a newbie and I dont know really what should I code in my view to show the captcha field.
I hope you can show me how.

Best.

captcha and validate can't work at the same time

Hi, I'm use laravel 5.2

When I am in accordance with the following word:

for Laravel 5.2+ Add \Illuminate\Session\Middleware\StartSession::class to $middleware in Kernel.php

the validate can't work.Submit the form without any response.When I remove after everything is ok.but capcha validate can't work. always incorrect.

please help me.

my validate code:

            $validate_messages = [
                'username.required' =>  "Account can't be blank.",
                'password.required' =>  "Password can't be blank.",
                'captcha_code.required' => "Validate code can't be blank.",
                'captcha' => "Validate code incorrect.",
            ];

            $this->validate($request, [
                'username'     => 'required',
                'password'     => 'required',
                'captcha_code' => 'required|captcha',
            ], $validate_messages);

            if ($this->validate->fails()) {
                return redirect('admin/login')->withInput()->withErrors($this->validator);
            }

Method validateCaptcha does not exist.

I have following issue: Method [validateCaptcha] does not exist.BadMethodCallException in Validator.php line 2615:

use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Mews\Captcha;
....
 protected $rules = array(
        'name'     => 'required',
        'captcha'  => 'required|captcha');
.....
 $validation = Validator::make($data, $this->rules);
......

ViewErrorBag always empty when adding code to Kernel.php with Laravel 5.2

I'm using laravel built-in AuthController,and when I add
\Illuminate\Session\Middleware\StartSession::class to $middleware in Kernel.php,the errorbag in login.blade.php returns empty,but I comment this line,the errorbag shows errors.

Another solution is not working too:
change line 26 in CaptchaServiceProvider to
$this->app['router']->get('captcha/{config?}', \Mews\Captcha\CaptchaController@getCaptcha')->middleware('web');

ErrorException include Classloader

Everything works fine on my localhost but when i'm uploading the stuff, this is my issue:

ErrorException in ClassLoader.php line 412:
include(/customers/b/f/a/smashpoint.be/httpd.www/webshop/vendor/intervention/image/src/Intervention/Image/ImageManager.php): failed to open stream: No such file or directory (View: /customers/b/f/a/smashpoint.be/httpd.www/webshop/resources/views/auth/register.blade.php)

Sombody who knows what the problem is?

Change getCaptcha route to match my custom route

In my system one user can have different accounts and can login with them in the same time and same browser. so i separate the session created for each account to be based in the route. captcha uses this route captcha/{config} and this doesn't match any route in the system.
where captcha/{config} called ? and how i can modify the route ? .
I recommend the route to be configurable or people set it manually.

Redirect's to captcha image after submitting the form.

Hello,
I have an issue with the latest version of laravel and your package.
Here is my code.
Validation:
$this->validate($request, [ 'Username' => 'required', 'Password' => 'required', 'captcha' => 'required|captcha', ]);
Routes:
Route::get('/guest/login', [ 'uses' => 'GuestController@getLogin', 'as' => 'guest.login', 'middleware' => ['guest'], ]); Route::post('/guest/login', [ 'uses' => 'GuestController@postLogin', 'middleware' => ['guest'], ]);
Session vuln. is already fixed.
Now when I'm submitting this, I will be redirected to this page: http://x/captcha/default?gVF1QaPb.
(If you can't understand, look at the URL of this video: https://youtu.be/i9YHpk6p038)
What could be the problem?

Kind regards & thank you for all help,
lNobodyl

Captcha validation always return invalid captcha

As shown in documentation I have setup captcha package and set my /captcha-test

I am able to see captcha and textbox but whenever I submit form I always getting error "validation.captcha" even if its not matter that captcha texts is right or wrong

am using laravel 5.0, please help, below is the form I setup in routes.php file

Route::any('captcha-test', function()
{
    if (Request::getMethod() == 'POST')
    {
        $rules = ['captcha' => 'required|captcha'];
        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails())
        {
            echo '<p style="color: #ff0000;">Incorrect!</p>';
        }
        else
        {
            echo '<p style="color: #00ff30;">Matched :)</p>';
        }
    }

    $form = '<form method="post" action="captcha-test">';
    $form .= '<input type="hidden" name="_token" value="' . csrf_token() . '">';
    //$form .= '<p>' . captcha_img() . '</p>';
    $form .= '<img src="'. Captcha::src('inverse') .'" id="register-captcha-image">';
    $form .= '<p><input type="text" name="captcha"></p>';
    $form .= '<p><button type="submit" name="check">Check</button></p>';
    $form .= '</form>';
    return $form;
});

//For setting captcha route
Route::get('/captcha/{config?}', function (\Mews\Captcha\Captcha $captcha, $config = 'default') {
    return $captcha->src($config);
});

Write the text for captcha

I would like a function that the programmer could to write the word what it appears at the image.

For example if I own a website about films, I could to have captcha like: "matrix", "oscar", "bigfish", "camera"...

I think this could be a good functionality.

the captcha_img() 404

Hello, here my problem:
when I according the introduce, all is go well
but the the captcha_img() can't found or the captcha_src() return 404
is there anything more need configured
so confused!

No Image Displayed

Installed package and pasted demo code in routes.php. Only the image placeholder, text field, and button are displayed - no image and no errors when hitting the route (http://satest.dev/captcha-test). Environment is Yosemite, Laravel 5.1, apache 2.4.1, php 5.6.11 with gd library. Any suggestions? Here is a screenshot of the page:

image

Don't delete the session unless verification is passed

Sorry for my poor English.
In Captcha.php#line 415

 $this->session->remove('captcha');

When I post a wrong captcha through AJAX, I have to refresh the CAPTCHA.
Maybe it's better to delete the SESSION after verification is passed rather then every time ?

Laravel 5.2: Captcha fails check even when it's correct

I'm using the Laravel 5.2 branch and for some reason, when you go to validate the captcha generated by {{ captcha_img() }} in a view, it will fail the validation and spit back "validation.captcha" which means that while there is no string that is available for use for captcha errors, the captcha failed anyway.

I am unable to debug this, but it seems to me that it can't cache the captcha to check. I believe I'm using the same library on another client's project, but I think that version is Laravel 5.0 and not 5.2.x.

Could someone please look into this? This is a bit of a pain because other than that, it's a solid captcha library. Thanks!

Add second parameters,I would like to repeat the verification

Add second parameters

if ( ! function_exists('captcha_check')) {
    /**
     * @param $value
     * @return bool
     */
    function captcha_check($value , $del = true)
    {
        return app('captcha')->check($value,$del);
    }
}

    public function check($value , $del = true)
    {
        if ( ! $this->session->has('captcha'))
        {
            return false;
        }

        $key = $this->session->get('captcha.key');

        if ( ! $this->session->get('captcha.sensitive'))
        {
            $value = $this->str->lower($value);
        }
        if($del){
            $this->session->remove('captcha');
        }

        return $this->hasher->check($value, $key);
    }

changing captcha after loading the page

Hi
I use {{ HTML::image(Captcha::img(), 'Captcha image') }} in my form.
after page loaded I can not submit it because captcha is wrong. I checked it by firebug and understood that url in src attribute in img tag is different!

Don't work

I get this error:

Symfony \ Component \ Debug \ Exception \ FatalErrorException
Call to undefined method Mews\Captcha\Facades\Captcha::img()

And I followed your steps to config, set alias and set providers

thaks

Captcha Check Problem When $formId Is Given

The mews captcha has a problem when $formId value is provided with img() function, like Captcha::img('registerForm'), because when Captcha validation is executed, this parameter ('registerForm') is not included in src/Mews/Captcha/CaptchaValidator.php and validation assumes that $formId value is empty, so it cannot find correct captcha session (which is captchaHash['registerForm']) and, of course, validation always fails.

Captcha verification error

Hello, while i was at my developing server the captcha was working fine, now i deployed to production server and the check is always false. Thanks in advance.

5.1 support.

Route based authentication doesn't work the same between 5.0 and 5.1, so changes are probably necessary for this package to work going forward.

As evidence, updating to 5.1 with this package installs results in the following from Composer:
[UnexpectedValueException]
Invalid route action: [App\Http\Controllers\AuthController]

The offending line was:

Route::group(['middleware' => 'captchad'],function(){
return [Route::post('contact', 'ContactController@store' )/,
Route::post('auth
', 'AuthController' )*/];
});

Commenting it out allowed my upgrade to proceed.

No image display with BOM utf8

Laravel 5.1 , xampp, windows system, the image can't display.
At the end, found the php file in window is format utf8 with bom, hope this will be help with other people.

99eb152e-40ec-11e5-9cd9-4df886b73fe0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.