Laravel Session - Public for Controller

3

I'm making a form that contains a Captcha . Captcha is generated by a PHP script that mounts an image.

And I put the script in the public folder of Laravel 4 .

When the Captcha code is generated it is placed in session:

session_start();
$_SESSION['numCaptcha'] = $code;

After submitting the form data, I send it to a Controller , which has the function:

public function enviaContato() {
   echo $_SESSION['numCaptcha'];
   die();

   # Verificação de Captcha
   if (empty(Session::get('numCaptcha')) || strcasecmp(Session::get('numCaptcha'), Input::get('numCaptcha')) != 0) {
      Session::flash('error', "Captcha Inválido");
   }
}

This way I did above is not taking the value of the session. I already did:

Session::get('numCaptcha')

But it also did not work.

Do you have any restrictions?
Can you do it differently?

Then, how to use the public session for the Controller .

    
asked by anonymous 26.08.2015 / 14:45

1 answer

2

First, you should check the Laravel setting. Laravel (like most frameworks) does not use the native PHP session. I can not remember if there is any way to set this up.

Thus, sessions of $_SESSION and Session::get are saved in different mechanisms (PHP saves in its default form, and Laravel saves in a file inside the app/storage folder).

So either your code has to be transformed into "pure php" or "pure laravel."

You mentioned in the comments that you could not install the library you want. So here is a captcha "on hand" (a solution in "almost pure laravel") that I used one of our system in Laravel - maybe useful in your case.

Route::get('captcha', function()
{

    $word = [0 => null, 1 => null];

    for ($i = 0; $i < 4; $i++) {
        $word[0] .= chr(mt_rand(97, 122));
        $word[1] .= chr(mt_rand(97, 122));
    }

    $word = implode(' ', $word);


    Session::put('captcha_word', $word);

    $font = public_path('recaptcha/fonts/recaptchaFont.ttf');

    $image = imagecreatetruecolor(172, 50);

    $color = imagecolorallocate($image, 0, 0, 0);
    $white = imagecolorallocate($image, 255, 255, 255);

    imagefilledrectangle($image, 0, 0, 172, 99, $white);
    imagettftext($image, 22, 0, 5, 35, $color, $font, Session::get('capcha_word'));

    $tempCapcha = tempnam(null, 'captcha');

    imagepng($image, $tempCapcha);

    return Response::make(File::get($tempCapcha), 200, ['Content-Type' => 'image/png']);
});

The verification would take place as follows:

if (Session::get('captcha_word') == Input::get('algum_input_com_captcha'))
{

}

And in HTML, to display Captcha, you could do this:

<img src="{{ URL::to('captcha') }}?{{ Str::random(8) }}" />

Note : Note that you need to save the font used by Captcha to the specified%% of the route.

Update : The excerpt of the path variable can be changed to make the code cleaner by using only one line to declare it.

So:

$word = trim(chunk_split(Str::random(8), 4, ' '));
    
26.08.2015 / 15:56