Captcha function in php

3 Steps Simple Captcha In PHP (Free Download)

Welcome to a tutorial on how to create a simple captcha in PHP. Have a website that is constantly being spammed by angry keyboard warriors? Time to put in some security and prevention measures. Let us walk through an example in this guide, without the use of any 3rd party frameworks – Read on!

TABLE OF CONTENTS

PHP CAPTCHA

All right, let us now get into the details of creating a simple PHP captcha.

STEP 1) PHP CAPTCHA CLASS

 if (session_status()==PHP_SESSION_NONE) < session_start(); >> // (C) PRIME THE CAPTCHA - GENERATE RANDOM STRING IN SESSION function prime () : void < $char = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $max = strlen($char) - 1; $_SESSION["captcha"] = ""; for ($i=0; $ilength; $i++) < $_SESSION["captcha"] .= substr($char, rand(0, $max), 1); >> // (D) DRAW THE CAPTCHA IMAGE function draw ($mode=0) : void < // (D1) FUNKY BACKGROUND IMAGE if (!isset($_SESSION["captcha"])) < exit("Captcha not primed"); >$captcha = imagecreatetruecolor($this->capW, $this->capH); list($bx, $by) = getimagesize($this->capB); $bx = ($bx-$this->capW) < 0 ? 0 : rand(0, ($bx-$this->capW)); $by = ($by-$this->capH) < 0 ? 0 : rand(0, ($by-$this->capH)); imagecopy($captcha, imagecreatefromjpeg($this->capB), 0, 0, $bx, $by, $this->capW, $this->capH); // (D2) RANDOM TEXTBOX POSITION $ta = rand(-20, 20); // random angle $tc = imagecolorallocate($captcha, rand(120, 255), rand(120, 255), rand(120, 255)); // random text color $ts = imagettfbbox($this->capFS, $ta, $this->capF, $_SESSION["captcha"]); if ($ta>=0) < $tx = rand(abs($ts[6]), $this->capW - (abs($ts[2]) + abs($ts[6]))); $ty = rand(abs($ts[5]), $this->capH); > else < $tx = rand(0, $this->capW - (abs($ts[0]) + abs($ts[4]))); $ty = rand(abs($ts[7]), abs($ts[7]) + $this->capH - (abs($ts[3]) + abs($ts[7]))); > imagettftext($captcha, $this->capFS, $ta, $tx, $ty, $tc, $this->capF, $_SESSION["captcha"]); // (D3) OUTPUT CAPTCHA if ($mode==0) < ob_start(); imagepng($captcha); $ob = base64_encode(ob_get_clean()); echo ""; > else < header("Content-type: image/png"); imagepng($captcha); imagedestroy($captcha); >> // (E) VERIFY CAPTCHA function verify ($check) < if (!isset($_SESSION["captcha"])) < exit("Captcha not primed"); >if ($check == $_SESSION["captcha"]) < unset($_SESSION["captcha"]); return true; >else < return false; >> > // (F) CAPTCHA OBJECT $PHPCAP = new Captcha();
  • (A) A whole bunch of captcha settings. Feel free to change to your own font, change the background, captcha image dimensions, etc…
  • (B & F) When $PHPCAP = new Captcha() is created, the constructor automatically starts the session if it is not already started.
  • (C To E) There are only 3 “real captcha functions”.
    • prime() Step 1 of the process, pretty much just generates a random string into $_SESSION[«captcha»] .
    • draw() Step 2 of the process, use this to output the HTML captcha image.
    • verify() When the user submits the form, use this to verify the user’s captcha against the session.

    STEP 2) GENERATE CAPTCHA IN HTML FORM

    prime(); $PHPCAP->draw(); ?>

    1. The “usual form fields”.
    2. Generate the captcha.
      • Captain Obvious to the rescue, require «1-captcha.php» to load the library.
      • Call the $PHPCAP->prime() function to generate a random captcha string into the session.
      • Call the $PHPCAP->draw() function to generate the captcha image.

    STEP 3) CAPTCHA VERIFICATION UPON SUBMISSION

    verify($_POST["captcha"])) < $result = "Congrats, CAPTCHA is correct."; print_r($_POST); >// (C) NOPE else

    On submitting the form, we only need to use $PHPCAP->verify($_POST[«captcha»]) to check if the user has entered the correct captcha – Proceed if the challenge passed, or show an error message if it failed.

    DOWNLOAD & NOTES

    Here is the download link to the example code, so you don’t have to copy-paste everything.

    SUPPORT

    600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

    EXAMPLE CODE DOWNLOAD

    Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

    That’s all for the code, and here are a few small extras that may be useful to you.

    MORE SECURITY

    Before the “security experts” start to bang on their keyboards, some additional security can be added to this simple captcha.

    • Impose a time limit/expiry on the captcha, 10 minutes for example – $_SESSION[«cexpire»] = strtotime(«now») + 600 .
    • Change the verify() function to also do a time check – if ($_SESSION[«cexpire»] > strototime(«now»)) < NOPE >.
    • Add a number of times a user can challenge the captcha. Decide what to do if the challenge fails too many times – Maybe require the user to click on an email verification link.
    • Very simply, use HTTPS.

    RELOADING THE CAPTCHA

    • “Move” the captcha creation to a separate mycap.php script – prime(); $PHPCAP->draw();
    • Modify 2-form.php , replace the captcha with an empty
    • Use Javascript fetch to load/reload the captcha.
      • var cap = () => fetch(«mycap.php»).then(res=>res.text()).then(txt=>document.getElementById(«cap»).innerHTML = txt);
      • window.addEventListener(«load», cap);
      • PHP Sessions (Very Simple Examples) – Code Boxx
      • GD Image Library – PHP
      • Changed your mind? Want something better? Check out the free Google reCaptcha.
      • Simple PHP Contact Form With Google reCaptcha – Code Boxx

      THE END

      Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better fight spam in your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

      Источник

      Создание простой капчи на PHP

      Captcha (капча) – это некий тест, который человек решает очень легко, а робот – нет (научить компьютер решать его крайне сложно и затруднительно).

      Другими словами, основная цель капчи – это определить кем является пользователь: человеком или роботом .

      Используется Captcha на сайте для защиты от спама и повышенной нагрузки, которые создают роботы. Капчу можно очень часто встретить в формах регистрации, входа, отправки сообщений, при скачивании файлов и многих других местах.

      В большинстве случаев капча отображается как некоторый искаженный или наложенный на фон текст, который посетителю сайта необходимо разобрать и ввести его в некоторое поле. Кроме текста на фоне используется и другие алгоритмы: найти среди множества картинок правильные, собрать пазл, переместить слайдер, нарисовать связь между несколькими картинками и т.д.

      Исходные коды капчи

      Исходные коды капчи расположены на GitHub: itchief/captcha.

      Форма с капчой

      Процесс разработки капчи представлен в виде следующих этапов:

      • верстка формы;
      • создания файла «captcha.php» для генерация кода капчи и изображения;
      • написание обработчика для формы (файл «process-form.php»);
      • написание JavaScript для отправки формы на сервер через AJAX и обработки ответа.

      Верстка формы

      Разработку Captcha начнём с создания формы. Для простоты форма будет состоять из капчи и кнопки отправить:

       
      Форма успешно отправлена!

      Генерация кода капчи и изображения

      Формирование кода капчи и изображения выполним в файле «captcha.php», который поместим в папку «/assets/php»:

      Генерирование текста капчи выполняется очень просто. Для этого в переменную $chars помещаются символы, из которых она может состоять. Далее с помощью функции str_shuffle() эти символы случайным образом перемешиваются и посредством substr выбирается первые шесть из них.

      Сохранении полученной капчи по умолчанию осуществляется в сессионную переменную. Но если хотите в куки, то установите переменной $use_session значение false :

      Если используете протокол HTTPS, то установите шестому аргументу значение true:

      setcookie('captcha', $value, $expires, '/', 'test.ru', true, true);

      Для отправки капчи клиенту создается изображение, имеющее фон «bg.png», на котором с помощью функции imagefttext() пишется текст капчи.

      Скрипт для обновления капчи на форме

      Код для обновления капчи при нажатию на кнопку .captcha__refresh :

      // функция для обновления капчи const refreshCaptcha = (target) => { const captchaImage = target.closest('.captcha__image-reload').querySelector('.captcha__image'); captchaImage.src = '/assets/php/captcha.php?r=' + new Date().getUTCMilliseconds(); } // получение кнопки для обновления капчи const captchaBtn = document.querySelector('.captcha__refresh'); // запуск функции refreshCaptcha при нажатии на кнопку captchaBtn.addEventListener('click', (e) => refreshCaptcha(e.target));

      Добавление обработчика к кнопке выполняется через addEventListener .

      Написание обработчика формы

      Для обработки формы создадим файл «process-form.php» в папке «/assets/php/»

      В этом файле будем сравнивать текст капчи, который пользователь ввел в форме с тем, который у нас хранится в сессии или куки.

       false]; $code = $_POST['captcha']; if (empty($code)) { $result['errors'][] = ['captcha', 'Пожалуйста введите код!']; } else { $code = crypt(trim($code), '$1$itchief$7'); $result['success'] = $captcha === $code; if (!$result['success']) { $result['errors'][] = ['captcha', 'Введенный код не соответствует изображению!']; } } echo json_encode($result);

      В качестве результата будем возвращать JSON. В случае успеха:

      В противном случае, success присвоим значение false , а в errors поместим ошибки:

      { success: false, errors: [ ['captcha', 'Пожалуйста введите код!'] ] }

      По умолчанию этот файл сравнивает капчу со значением, находящимся в сессии. Если в «captcha.php» сохраняете капчу в куки, то здесь необходимо закомментировать секцию 1a и раскомментировать 1b:

      // 1a //session_start(); //$captcha = $_SESSION['captcha']; //unset($_SESSION['captcha']); //session_write_close(); // 1b $captcha = $_COOKIE['captcha']; unset($_COOKIE['captcha']); setcookie('captcha', '', time() - 3600, '/', 'test.ru', false, true);

      Если используете протокол HTTPS, то замените шестой аргумент на значение true :

      //setcookie('captcha', '', time() - 3600, '/', 'test.ru', true, true);

      JavaScript для отправки формы на сервер через AJAX

      Код для отправки формы на сервер через AJAX и обработки полученного результата:

      const form = document.querySelector('#form'); form.addEventListener('submit', (e) => { e.preventDefault(); try { fetch(form.action, { method: form.method, credentials: 'same-origin', body: new FormData(form) }) .then((response) => { return response.json(); }) .then((data) => { document.querySelectorAll('input.is-invalid').forEach((input) => { input.classList.remove('is-invalid'); input.nextElementSibling.textContent = ''; }); if (!data.success) { refreshCaptcha(form.querySelector('.captcha__refresh')); data.errors.forEach(error => { console.log(error); const input = form.querySelector(`[name="${error[0]}"]`); if (input) { input.classList.add('is-invalid'); input.nextElementSibling.textContent = error[1]; } }) } else { form.reset(); form.querySelector('.captcha__refresh').disabled = true; form.querySelector('[type=submit]').disabled = true; document.querySelector('.form-result').classList.remove('d-none'); } }); } catch (error) { console.error('Ошибка:', error); } }); 

      В этом коде отправка данных через AJAX выполняется посредством fetch() . Получение данных формы с использованием FormData .

      Для отправки и получения cookie посредством fetch() установим:

      Если в success находится значение false , то будем помечать поля, которые не прошли валидацию и выводить подсказки:

      if (!data.success) { refreshCaptcha(form.querySelector('.captcha__refresh')); data.errors.forEach(error => { console.log(error); const input = form.querySelector(`[name="${error[0]}"]`); if (input) { input.classList.add('is-invalid'); input.nextElementSibling.textContent = error[1]; } }) }

      Капча не прошла проверку

      Если в success содержится значение true , то будем очищать поля и выводить сообщение об успешной отправки формы:

      form.reset(); form.querySelector('.captcha__refresh').disabled = true; form.querySelector('[type=submit]').disabled = true; document.querySelector('.form-result').classList.remove('d-none');

      Источник

      Читайте также:  What things can you do with java
Оцените статью