Captcha module in php

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Simple php server based captcha using GD

License

pstimpel/phpcaptcha

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

readme.md

Since Google and others are abusing Captchas to be tracking utilities, it was time to write a server based Captcha. Since the data are processed on your webserver only, this Captcha is GDPR safe. PHP Captcha does not forward any data away from your server. You do not need to mention it in your privacy policy. But of course I would like it very much, if you could add a reference to this project.

PHP Captcha is available under the terms of GPLv3. See License for more information.

PHP Captcha is using GD to generate images. PHP5 and PHP7 are supported.

  1. Download the latest release here: https://github.com/pstimpel/phpcaptcha/releases
  2. Unpack the content of the zip into a folder on your webserver, let’s say to modules in your webroot
  3. Use your webbrowser and browse to /modules/phpcaptcha-/index.php
  4. If 3. works fine, you could configure PHP Captcha by editing /modules/phpcaptcha-/config.php

_Do not attempt a change of your configuration until you finished step 3 of the installation with success! _

stringLength: How many characters to use for the captcha, default is 6

charsToUse Which characters to choose from, default is abcdefghkmnprstuvwxyz23456789 , it might be a good idea to skip characters like I and 1 for avoiding confusion

strictLowerCase: Limit captcha to lower case, default is true , if there are no upper case characters in your charsToUse , this option is useless

bgcolor.r: Red value of background color, default is 0, valid from 0 to 255

bgcolor.g: Green value of background color, default is 0, valid from 0 to 255

bgcolor.b: Blue value of background color, default is 0, valid from 0 to 255

textcolor.r: Red value of text color, default is 255, valid from 0 to 255

textcolor.g: Green value of text color, default is 255, valid from 0 to 255

textcolor.b: Blue value of text color, default is 255, valid from 0 to 255

font: Name of TTF font to use, default is ‘Lato-Regular.ttf’, but you can use any TTF font you like.

Font Lato is GPL, OFL and Public Domain by Łukasz Dziedzic, can be found at https://www.1001freefonts.com/lato.font

sessionName: The name of the session var PHP Captcha is using to store the text from the captcha, default is phpcaptcha , which is accessible in $_SESSION[‘phpcaptcha’]

size.width: The width of the generated image, default is 200

size.height: The height of the generated image, default is 50

fontsize: The font size to be used, default is 25

numberOfLines: The number of lines to draw across the image for creating some small confusion to OCR, default is 6

thicknessOfLines: The thickness per line, default is 2

linecolor.r: Red value of line color, default is 128, valid from 0 to 255

linecolor.g: Green value of line color, default is 128, valid from 0 to 255

linecolor.b: Blue value of line color, default is 128, valid from 0 to 255

There is a Demo available, if you unzipped the package at your webserver. Just navigate to the demo subfolder using your webbrowser. If GD is missing, PHP Captcha will detect it and throw an error. If you misconfigured PHP Captcha, it will try to run on defaults, or throw an error depending on the type of your failure.

If it was installed and configured well, just reference /modules/phpcaptcha/index.php as image in your html form.

 

You will have to add a textfield to your form as well, so the user can type in what he/she/it sees on the captcha image. Let’s do it like this:

Now, make a check where you evaluate the form data. A simple

if($_POST['captchatext'] == $_SESSION['phpcaptcha']) < //Captcha solution OK >else < //Captcha solution wrong >

will do. Of course you should run checks like isset() on both variables before.

However, you are ready to go, congrats!

About

Simple php server based captcha using GD

Источник

Создание простой капчи на 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');

Источник

Читайте также:  Javascript число с нулями
Оцените статью