PHP code example of arodu / utilcake

1. Go to this page and download the library: Download arodu/utilcake library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

arodu / utilcake example snippets


public function bootstrap(){
    parent::bootstrap();
    $this->addPlugin('UtilCake');
}

public function initialize(): void{
  parent::initialize();
  $this->loadComponent('UtilCake.ReCaptcha', [
    'public_key'=>'RECAPTCHA_PUBLIC_KEY',
    'secret_key'=>'RECAPTCHA_SECRET_KEY',
  ]);
}

// any action
public function action(){
  // ...
  if ($this->request->is('post')) {
    if($this->ReCaptcha->verify($this->request->getData())){
      // when the verification is successful
      // ...
    }else{
      // when the verification is not successful
      $this->Flash->error(__('reCaptcha failed, try again'));
    }
  }
  // ...
}

echo $this->Form->create(null, ['id'=>'form-id']);
  // ...
echo $this->Form->end();

$this->ReCaptcha->script('#form-id');

echo $this->GoogleLogin->link(__('Sign in with Google'),
  ['class' => 'btn btn-block btn-danger', 'escape' => false]
);

public function initialize(): void{
  parent::initialize();
  $this->loadComponent('UtilCake.GoogleLogin', [
    'client_id' => GOOGLE_CLIENT_ID,
    'client_secret' => GOOGLE_CLIENT_SECRET,
    'redirect_uri' => Router::url([
        'controller' => 'Users',
        'action' => 'googleLogin',
        'prefix' => false,
        '_full' => true
      ]),
  ]);
}

//...

public function googleLogin() {
  if (!empty($this->request->getQuery('code'))) {
    try {
      $data = $this->GoogleLogin->getAccessToken($this->request->getQuery('code'));
      $user_profile_info = $this->GoogleLogin->getUserProfileInfo($data['access_token']);

      $user = $this->Users->find()
        ->where(['Users.email' => $user_profile_info['email']])
        ->first();

      if ($user) {
        $this->Authentication->setIdentity($user);
        $target = $this->Authentication->getLoginRedirect() ?? '/';
        return $this->redirect($target);
      }

      $this->Flash->error('Invalid google login');
    } catch (\Exception $e) {
      throw new NotFoundException($e->getMessage());
    }
  }

  return $this->redirect(['action' => 'login']);
}