สำหรับกระทู้นี้จะแนะนำการเรียกใช้ reCaptcha สำหรับใช้ในกรณีที่ในฟอร์มนั้นไม่ได้เรียกจาก XML Form
ตัวอย่างโค้ด
โค้ด: เลือกทั้งหมด
<?php
// กำหนด class ที่เราจะเรียกใช้งาน ที่จำเป็นจะมี 2 ตัวนี้
use Joomla\CMS\Factory;
use Joomla\CMS\Captcha\Captcha;
// ดึงค่าจาก Global Configuration ของ Joomla ว่าใช้ reCaptcha ตัวไหนอยู่
$plugin = Factory::getConfig()->get('captcha');
// ถ้ามีการกำหนด reCaptcha ใน Global Configuration ให้ทำงานใน if
if ($plugin)
{
// เรียก class Captcha มาใช้
$captcha = new Captcha($plugin, array ());
// ใช้ method ชื่อ display สำหรับแสดงผล สามารถกำหนด ชื่อ และ ไอดี ได้ ในตัวอย่างจะใช้ my_captcha
echo $captcha->display('my_captcha', 'my_captcha');
}
จากนั้น หลังจากที่ผู้ใช้งานกด Submit ข้อมูลเข้ามาในระบบ จะต้องมีการเช็คข้อมูลของตัว reCaptcha ด้วย
โค้ด: เลือกทั้งหมด
<?php
// กำหนด class ที่เราจะเรียกใช้งาน ที่จำเป็นจะมี 2 ตัวนี้
use Joomla\CMS\Factory;
use Joomla\CMS\Captcha\Captcha;
// เรียกใช้ object ของ Application อันนี้จะใช้แสดงข้อความแจ้ง กับ ย้ายหน้าเว็บ
$app = Factory::getApplication();
// ดึงค่าจาก Global Configuration ของ Joomla ว่าใช้ reCaptcha ตัวไหนอยู่
$plugin = Factory::getConfig()->get('captcha');
// ถ้ามีการกำหนด reCaptcha ใน Global Configuration ให้ทำงานใน if
if ($plugin)
{
// เรียกไฟล์ภาษาของตัว captcha มาใช้ กรณีมี error หรือ ข้อความแจ้งเตือน
$language = Factory::getLanguage();
$language->load('plg_captcha_' . $plugin, JPATH_ROOT . '/administrator');
// เรียก class Captcha มาใช้
$captcha = new Captcha($plugin, array ());
// เช็คค่าของ reCaptcha ที่ส่งมาจากฟอร์ม
if (!$captcha->checkAnswer(null))
{
// กรณีค่าของ reCaptcha ไม่ถูกต้อง ให้ส่งข้อความแจ้ง และ ย้ายหน้ากลับไปหน้าฟอร์ม
$error = $captcha->getError();
$app->enqueueMessage($error, 'warning');
$app->redirect(JRoute::_('index.php?option=com_mycomponent&view=myview'));
}
}