Hello, I’m using Slim 3.x with several forms. Now I need to protect them using recaptcha v3, so I assumed that a trait should be the right way to DRY
I have a Helpers folder under app
/–app/
|–Controllers
|–Helpers
|–Middleware
|–Models
|–Validation
So I’ve created a trait under Helpers
<?php
namespace App\Helpers;
trait Captcha
{
public function validateCaptcha($token, $action)
{
// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = $this->container->get('settings')['captcha']['secret'];
$recaptcha_response = $recaptcha;
// Make and decode POST request:
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
// Take action based on the score returned:
if ($recaptcha->score >= 0.5 && $recaptcha->action === $action) {
return true;
}
return false;
}
}
Then, in my controller I have
use App\Helpers\Captcha;
class ProccessFormController extends Controller
{
use Captcha;
public function store($request, $response, $args)
{
if (! validateCaptcha($getParam->recaptcha_response, 'action1')) {
$this->flash->addMessage('error', 'Captcha error');
return $response->withRedirect($this->router->pathFor('home'));
}
......
}
When submitting a form, controller fires an error
**Type:** Error
**Message:** Call to undefined function App\Controllers\validateCaptcha()
**File:** /home/dummy/app/Controllers/ProccessFormController.php
**Line:** 22
If I put validateCaptcha() function inside my controller, everything works fine, so the point is that my controller is unable to load and use the trait.
Thanks for any idea on how to solve it.