- Saved searches
- Use saved searches to filter your results more quickly
- License
- Gregwar/Captcha
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- Создание простой капчи на PHP
- Исходные коды капчи
- Верстка формы
- Генерация кода капчи и изображения
- Скрипт для обновления капчи на форме
- Написание обработчика формы
- JavaScript для отправки формы на сервер через AJAX
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.
License
Gregwar/Captcha
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
You can create a captcha with the CaptchaBuilder :
use Gregwar\Captcha\CaptchaBuilder; $builder = new CaptchaBuilder; $builder->build();
You can then save it to a file :
header('Content-type: image/jpeg'); $builder->output();
Or inline it directly in the HTML page:
$builder->inline(); ?>" />
You’ll be able to get the code and compare it with a user input :
// Example: storing the phrase in the session to test for the user // input later $_SESSION['phrase'] = $builder->getPhrase();
You can compare the phrase with user input:
if($builder->testPhrase($userInput)) < // instructions if user phrase is good > else < // user phrase is wrong >
You can use theses functions :
- __construct($phrase = null), constructs the builder with the given phrase, if the phrase is null, a random one will be generated
- getPhrase(), allow you to get the phrase contents
- setDistortion($distortion), enable or disable the distortion, call it before build()
- isOCRReadable(), returns true if the OCR can be read using the ocrad software, you’ll need to have shell_exec enabled, imagemagick and ocrad installed
- buildAgainstOCR($width = 150, $height = 40, $font = null), builds a code until it is not readable by ocrad
- build($width = 150, $height = 40, $font = null), builds a code with the given $width, $height and $font. By default, a random font will be used from the library
- save($filename, $quality = 80), saves the captcha into a jpeg in the $filename, with the given quality
- get($quality = 80), returns the jpeg data
- output($quality = 80), directly outputs the jpeg code to a browser
- setBackgroundColor($r, $g, $b), sets the background color to force it (this will disable many effects and is not recommended)
- setBackgroundImages(array($imagepath1, $imagePath2)), Sets custom background images to be used as captcha background. It is recommended to disable image effects when passing custom images for background (ignore_all_effects). A random image is selected from the list passed, the full paths to the image files must be passed.
- setInterpolation($interpolate), enable or disable the interpolation (enabled by default), disabling it will be quicker but the images will look uglier
- setIgnoreAllEffects($ignoreAllEffects), disable all effects on the captcha image. Recommended to use when passing custom background images for the captcha.
- testPhrase($phrase), returns true if the given phrase is good
- setMaxBehindLines($lines), sets the maximum number of lines behind the code
- setMaxFrontLines($lines), sets the maximum number of lines on the front of the code
If you want to change the number of character, you can call the phrase builder directly using extra parameters:
use Gregwar\Captcha\CaptchaBuilder; use Gregwar\Captcha\PhraseBuilder; // Will build phrases of 3 characters $phraseBuilder = new PhraseBuilder(4); // Will build phrases of 5 characters, only digits $phraseBuilder = new PhraseBuilder(5, '0123456789'); // Pass it as first argument of CaptchaBuilder, passing it the phrase // builder $captcha = new CaptchaBuilder(null, $phraseBuilder);
You can also pass directly the wanted phrase to the builder:
// Building a Captcha with the "hello" phrase $captcha = new CaptchaBuilder('hello');
If you want to see an example you can have a look at the demo/form.php , which uses demo/session.php to render a captcha and check it after the submission
You can have a look at the following repository to enjoy the Symfony 2 bundle packaging this captcha generator : https://github.com/Gregwar/CaptchaBundle
You can use the following extension for integrating with Yii2 Framework : https://github.com/juliardi/yii2-captcha
This library is under MIT license, have a look to the LICENSE file
Создание простой капчи на PHP
Captcha (капча) – это некий тест, который человек решает очень легко, а робот – нет (научить компьютер решать его крайне сложно и затруднительно).
Другими словами, основная цель капчи – это определить кем является пользователь: человеком или роботом .
Используется Captcha на сайте для защиты от спама и повышенной нагрузки, которые создают роботы. Капчу можно очень часто встретить в формах регистрации, входа, отправки сообщений, при скачивании файлов и многих других местах.
В большинстве случаев капча отображается как некоторый искаженный или наложенный на фон текст, который посетителю сайта необходимо разобрать и ввести его в некоторое поле. Кроме текста на фоне используется и другие алгоритмы: найти среди множества картинок правильные, собрать пазл, переместить слайдер, нарисовать связь между несколькими картинками и т.д.
Исходные коды капчи
Исходные коды капчи расположены на GitHub: itchief/captcha.
Процесс разработки капчи представлен в виде следующих этапов:
- верстка формы;
- создания файла «captcha.php» для генерация кода капчи и изображения;
- написание обработчика для формы (файл «process-form.php»);
- написание JavaScript для отправки формы на сервер через AJAX и обработки ответа.
Верстка формы
Разработку Captcha начнём с создания формы. Для простоты форма будет состоять из капчи и кнопки отправить:
Форма успешно отправлена!