Chuyển tới nội dung
Home » Captcha Code In Php | Php Captcha With Contact Form Example

Captcha Code In Php | Php Captcha With Contact Form Example

Login form with captcha in PHP || Captcha integration with Source Code

captcha.php

This file is used to generate a captcha image.



phpcaptcha('#162453','#fff',120,40,10,25); ?>

Found This Useful? Share This Page!

How to Create Captcha in PHP 8 Contact Form

The Internet is a place that is full of hackers and scammers, and hackers create malicious scripts to get access to your application.

SQL injection, XSS attack, Bulk spam mails may bring tons of trouble for you.

Spam can enhance the server load and put your web application down, which leads to the unavailability of your web application.

It directly affects site users or customers. In return, it impacts on your online business.

Captcha is the best solution for this curse. It protects from unwanted access and spam bots.

It prevents bots from sending useless data through the contact form in php.

CAPTCHA is a randomly generated code. It is produced in run time. It can be seen in various forms.

For instance, here are the common types of Captcha:

  • Graphical (image)
  • Text
  • Audio

The captcha code is a random number, which needs to be filled by the user. Validation makes sure whether a real human enters the value, basically a bot faces a problem in filling the captcha code. This way, it prevents spam.

demo.php

This file is used to obtain submitted form data and used to validate the captcha image.



The Validation code does not match!";// Captcha verification is incorrect. }else{// Captcha verification is Correct. Final Code Execute here! $msg="

The Validation code has been matched.

"; } } ?>


Validation code:
Can't read the image? click

here

to refresh.

Login form with captcha in PHP || Captcha integration with Source Code
Login form with captcha in PHP || Captcha integration with Source Code

HTML Contact Form with Captcha

Created a contact form using HTML and CSS with two Captcha fields in one field generate Captcha image in other field enter the value from captcha image to pass the validation.

Create scripts/ folder, create contact_form.php file then put the following code in the file.

To add custom styling in the form use the following CSS.

Create assets/css/ folder, create style.css file then put the following code in the file.


.container { max-width: 500px; margin: 50px auto; text-align: left; font-family: sans-serif; } form { border: 1px solid #1A33FF; background: #ecf5fc; padding: 40px 50px 45px; } .form-control:focus { border-color: #000; box-shadow: none; } label { font-weight: 600; } .error { color: red; font-weight: 400; display: block; padding: 6px 0; font-size: 14px; } .form-control.error { border-color: red; padding: .375rem .75rem; }

Create PHP Captcha with GD Library

Set captcha code in the PHP session. Generate a random number with 6 characters.

This will be out security code. Create a basic captcha using the GD library built-in functions. This code will generate the captcha image.

Create scripts/ folder, create captcha.php file and insert the given code in the file.

You can also create the advance captcha with customizable code length, character sets, and Unicode support, you can also customize captcha font using TTF font.

Further features like image distortion, random lines, noise, alphanumeric captcha characters.

captcha code generation using PHP
captcha code generation using PHP

Conclusion

In this tutorial, we successfully created a simple Captcha in PHP from scratch and implemented it with the PHP contact form.

In this article, we’ll see how to generate a very simple and effective Captcha Image in PHP. Captchas are smart (at least most of the time) verification systems that prevent sites from bots that steal data from the site or unnecessarily increases the traffic of the site. In addition to preventing spams, Captchas are also used as a layer-of-protection against prevent DDoS attacks by malicious hackers.

So long-story-short Captchas are super-useful in this 21st Century. Captchas being so important nowadays (for security reasons mainly) should almost always be implemented in a server-side language like PHP and not client-sided JavaScript. The reason being that it becomes super-easy for any “robot” to bypass the security since the verification is done on the client-side (and it doesn’t even involve any image processing). So for that reason, we’ll make the Image Captcha in PHP using the GD (Graphics Draw) library which is usually installed by default.

For this article we won’t use any advanced GD functions. But if you want to learn more about GD then you read the various GeeksforGeeks articles about it.

So the main idea of creating an image-captcha is to first have a captcha.php which would start a session and generate captchas.

Bước 1 : Để tạo Captcha, trước tiên chúng ta tạo file captcha.php. Tham khảo code dưới đây :

Bước 2 : Tạo file index.php để tạo form nhập và kiểm tra Captcha :

Định dạng lại form bằng CSS :

Bước 3 : Chạy file index.php, ta được kết quả ban đầu :

Nếu ta nhập đúng mã thì kết quả sẽ thông báo Right captcha như dưới và ngược lại :

Thiết kế và lập trình Website PHP, Laravel chuyên nghiệp – FullStack
Lập trình ứng dụng trên nền tảng android
Lập trình Ứng dụng với Công nghệ ASP.NET Core MVC, WebAPI, ReactJS – FullStack
Lập trình ứng dụng với WINDOWS FORM
Lập trình ứng dụng với JAVA (FORM)
Thiết kế và lập trình Ứng dụng với công nghệ Java (Java Framework springBoot, hibernate,…) – FullStack
Thiết kế và lập trình website với công nghệ HTML5, CSS3, Javascript, Bootstrapt 4, Jquery
Lập trình frontend với reacjs (Full)

When allowing users to enter data into our website, we need to check whether the data is entered by the human. Otherwise, people will use robots to push the bulk of unwanted data into the website.

Allowing malicious access will cause a lot of problems. For example, XSS attack or SQL injection and more.

Sometimes it will increase server load and let it down. It may annoy your regular users due to the unavailability of the website.

Captcha is one of the best remedies for this hazard. It prevents anonymous access and stops robots from sending data.

CAPTCHA is an unpredictable random code. It is generated in run time. It can be in a variety of modes. For example,

On submitting the user input, it validates the captcha code entered by the user. This validation will help to capture the robot not entering the captcha code.

This is to know how to generate Captcha code using core PHP. I have created this example without using any third-party plugins.

It has minimal and structural code by which you can have a clear idea about how it works.

It contains a contact form to get names, email, message subject and messages from the users. I have creates a captcha and displays it in the form. The captcha is mandatory to submit the form.

I used PHP built-in GD library to create captcha images. I generate a random key and supply it to the captcha image layer.

I have used the PHP session to manage the current captcha session.

I created a contact form and render a Captcha input into it.

This code shows the HTML to display the form with the Captcha code.

The input element named captcha_code is the target to display the captcha.

I used CSS to set the captcha image as the background of this input field. I did this for the design aesthetics of embedding the captcha.

We can also show the captcha image as an individual image element in the form.


<br /> Contact Form with PHP Captcha<br />

Create Database Connection

In order to establish connection between server and PHP application, make sure to config/ folder, create database.php file and the below code.



setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Database connection failed: " . $e->getMessage(); } ?>

Simple captcha system in PHP + source code | real time image creation | Quick programming tutorial
Simple captcha system in PHP + source code | real time image creation | Quick programming tutorial

Add CAPTCHA to Contact Form

Add captcha with the contact form, and we get the captcha code from the session that we declared earlier.

We have not validated the form, but we validated the captcha. When there is no captcha entered, the user will be notified with the required captcha message.

When the user entered the wrong captcha user will also be alerted with a message.

Create scripts/ folder, create contact_form.php file and insert the given code in the file.



"alert-danger", "message" => "Please enter the captcha." ); } else if($_SESSION['CAPTCHA_CODE'] == $captchaUser){ $captchaError = array( "status" => "alert-success", "message" => "Your form has been submitted successfuly." ); } else { $captchaError = array( "status" => "alert-danger", "message" => "Captcha is invalid." ); } } ?>

Include the contact_form.php in the index.php file to bind the captcha with contact form.


<br /> PHP Contact Form with Captcha<br />







PHP


session_start();


$captcha


= rand(1000, 9999);


$_SESSION


"captcha"


] =


$captcha


$im


= imagecreatetruecolor(50, 24);


$bg


= imagecolorallocate(


$im


, 22, 86, 165);


$fg


= imagecolorallocate(


$im


, 255, 255, 255);


imagefill(


$im


, 0, 0,


$bg


);


imagestring(


$im


, rand(1, 7), rand(1, 7),


rand(1, 7),


$captcha


$fg


);


header("Cache-Control: no-store,


no-cache, must-revalidate");


header(


'Content-type: image/png'


);


imagepng(


$im


);


imagedestroy(


$im


);


?>

When you can run captcha.php, you should have a small image with a captcha printed on it. Now only thing we need to do is create a test.php which uses captcha.php and validates captcha based on user’s input. For this example, we’ll keep it simple. When the user gives us a wrong captcha we print an error message and when he gives us a correct captcha we might want to redirect the user to a different URL but for now, we’ll simply print a message.

Create Login & Registration Form With Captcha & Session In PHP & MySQL | Login With Captcha In PHP
Create Login & Registration Form With Captcha & Session In PHP & MySQL | Login With Captcha In PHP

Adding the CAPTCHA to Our PHP Contact Form

Now that we have created our CAPTCHA, it's time to add it to our contact form. We will use the contact form from my previous tutorial on how to create a PHP contact form and add the CAPTCHA just above the Send Message button.

We will be using sessions to store the CAPTCHA text and then validate the text entered by website visitors. Here is the complete code of our captcha.php file:

session_start();

$permitted_chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ';

function generate_string($input, $strength = 10) {

$input_length = strlen($input);

$random_string = '';

10

for($i = 0; $i < $strength; $i++) {

11

$random_character = $input[mt_rand(0, $input_length - 1)];

12

$random_string .= $random_character;

13

14

15

return $random_string;

16

17

18

$image = imagecreatetruecolor(200, 50);

19

20

imageantialias($image, true);

21

22

$colors = [];

23

24

$red = rand(125, 175);

25

$green = rand(125, 175);

26

$blue = rand(125, 175);

27

28

for($i = 0; $i < 5; $i++) {

29

$colors[] = imagecolorallocate($image, $red - 20*$i, $green - 20*$i, $blue - 20*$i);

30

31

32

imagefill($image, 0, 0, $colors[0]);

33

34

for($i = 0; $i < 10; $i++) {

35

imagesetthickness($image, rand(2, 10));

36

$line_color = $colors[rand(1, 4)];

37

imagerectangle($image, rand(-10, 190), rand(-10, 10), rand(-10, 190), rand(40, 60), $line_color);

38

39

40

$black = imagecolorallocate($image, 0, 0, 0);

41

$white = imagecolorallocate($image, 255, 255, 255);

42

$textcolors = [$black, $white];

43

44

$fonts = [dirname(__FILE__).'\fonts\Acme.ttf', dirname(__FILE__).'\fonts\Ubuntu.ttf', dirname(__FILE__).'\fonts\Merriweather.ttf', dirname(__FILE__).'\fonts\PlayfairDisplay.ttf'];

45

46

$string_length = 6;

47

$captcha_string = generate_string($permitted_chars, $string_length);

48

49

$_SESSION['captcha_text'] = $captcha_string;

50

51

for($i = 0; $i < $string_length; $i++) {

52

$letter_space = 170/$string_length;

53

$initial = 15;

54

55

imagettftext($image, 24, rand(-15, 15), $initial + $i*$letter_space, rand(25, 45), $textcolors[rand(0, 1)], $fonts[array_rand($fonts)], $captcha_string[$i]);

56

57

58

header('Content-type: image/png');

59

imagepng($image);

60

imagedestroy($image);

61

?>

The fonts that you want to use will go into the fonts directory. Now, you simply have to add the following HTML code above the Send Message button from our previous tutorial on creating a contact form in HTML and PHP.

Sometimes, the PHP form and CAPTCHA text will be hard to read even for humans. In these situations, we want them to be able to ask for a new form with CAPTCHA in a user-friendly manner. The redo icon above helps us do exactly that. All you have to do is add the JavaScript below on the same page as the HTML for the contact form.

var refreshButton = document.querySelector(".refresh-captcha");

refreshButton.onclick = function() {

document.querySelector(".captcha-image").src = 'captcha.php?' + Date.now();

After integrating the PHP form and CAPTCHA and adding a refresh button, you should get a form that looks like the image below. Take a look at the following CAPTCHA PHP example:

The final step in our integration of the form with CAPTCHA we created with the contact form involves checking the PHP form and CAPTCHA value input by users when filling out the form and matching it with the value stored in the session. Update the contact.php file from the previous tutorial to have the following code.

session_start();

if($_POST) {

$visitor_name = "";

$visitor_email = "";

$email_title = "";

$concerned_department = "";

10

$visitor_message = "";

11

12

if(isset($_POST['captcha_challenge']) && $_POST['captcha_challenge'] == $_SESSION['captcha_text']) {

13

14

if(isset($_POST['visitor_name'])) {

15

$visitor_name = filter_var($_POST['visitor_name'], FILTER_SANITIZE_STRING);

16

17

18

if(isset($_POST['visitor_email'])) {

19

$visitor_email = str_replace(array("\r", "\n", "%0a", "%0d"), '', $_POST['visitor_email']);

20

$visitor_email = filter_var($visitor_email, FILTER_VALIDATE_EMAIL);

21

22

23

24

if(isset($_POST['email_title'])) {

25

$email_title = filter_var($_POST['email_title'], FILTER_SANITIZE_STRING);

26

27

28

if(isset($_POST['concerned_department'])) {

29

$concerned_department = filter_var($_POST['concerned_department'], FILTER_SANITIZE_STRING);

30

31

32

if(isset($_POST['visitor_message'])) {

33

$visitor_message = htmlspecialchars($_POST['visitor_message']);

34

35

36

if($concerned_department == "billing") {

37

$recipient = "[email protected]";

38

39

else if($concerned_department == "marketing") {

40

$recipient = "[email protected]";

41

42

else if($concerned_department == "technical support") {

43

$recipient = "[email protected]";

44

45

else {

46

$recipient = "[email protected]";

47

48

49

$headers = 'MIME-Version: 1.0' . "\r\n"

50

.'Content-type: text/html; charset=utf-8' . "\r\n"

51

.'From: ' . $visitor_email . "\r\n";

52

53

if(mail($recipient, $email_title, $visitor_message, $headers)) {

54

echo '

Thank you for contacting us. You will get a reply within 24 hours.

';

55

} else {

56

echo '

We are sorry but the email did not go through.

';

57

58

} else {

59

echo '

You entered an incorrect Captcha.

';

60

61

62

} else {

63

echo '

Something went wrong

';

64

65

66

?>

We updated this file to first check if the CAPTCHA PHP code value stored in the session is the same as the value input by the user. If they are different, we simply tell the visitors that they entered an incorrect CAPTCHA. You can handle the situation differently based on what your project needs.

Contact Form with PHP Captcha

Name Email
Subject
Content
Captcha Code:





The captchaImageSource.php file is the background source of the captcha element. This file creates a random token and embeds it on a dynamically created image source.

The below PHP code shows how it works. It requires the Captcha.php Model class. It has methods to create, manage and validate the captcha.

After creating captcha images, the renderCaptchaImage() function tiles the captcha onto the form. It sends a header for returning captcha resources to the browser.



getCaptchaCode(6); $captcha->putSession('captcha_code', $captcha_code); $imageData = $captcha->createCaptchaImage($captcha_code); $captcha->renderCaptchaImage($imageData); ?>

In this PHP class, the getCaptchaCode() creates a 6 digit token. It is to display a random key in the captcha layer. I used PHP random_bytes(64) to get the random key.

I used a PHP session to store the captcha and validate it with the user data.

The create captcha image function generates the captcha image dynamically. With the use of the PHP GD library function, this is quite easy to generate.

It creates a JPEG resource and returns it to the contact form. The below code shows the Captcha.php class functions.



getSession("captcha_code"); if ($capchaSessionData == $formData) { $isValid = true; } return $isValid; } } ?>

After generating and displaying the captcha code, the next step is validation.

After the form submits, the validation takes place in the PHP end. The below code shows how it compares user data with the current captcha session.

It returns a boolean true or false based on which the process will go forward.

I used the database to store the contact data once the captcha validation returns true. This code also shows form-data sanitization with PHP filter_var() function.



0) { $userCaptcha = filter_var($_POST["captcha_code"], FILTER_SANITIZE_STRING); $isValidCaptcha = $captcha->validateCaptcha($userCaptcha); if ($isValidCaptcha) { $userName = filter_var($_POST["userName"], FILTER_SANITIZE_STRING); $userEmail = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL); $subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING); $content = filter_var($_POST["content"], FILTER_SANITIZE_STRING); require_once "./Model/Contact.php"; $contact = new Contact(); $insertId = $contact->addToContacts($userName, $userEmail, $subject, $content); if (! empty($insertId)) { $success_message = "Your message received successfully"; } } else { $error_message = "Incorrect Captcha Code"; } } ?>

This is the output screenshot for a contact form with a custom captcha. This screen shows a text captcha code in an image format.

The green division shows acknowledgment denoting the successful submission of the form with a valid captcha.

Once the user entered invalid captcha, the PHP captcha validation script will return false. Then, it will send the error message to update the UI as shown below.

Very good, thank you.

I am very much gratefull to you maam. I get many things to learn from you.

how to add the php capcha to a form which is sending form data as emailPlease reply to my emailRegards

thank you.

Create a Simple Captcha Script Using PHP

We all have encountered captcha validation in online web forms. Basically captcha are used to check that weather you are human or a bot. These captcha images contains some readable text with some noise, shape, distortion, lines and dots, which are readable by human and who can write it into the captcha input field to confirm that user is human, not a bot.

There are ready made third party captcha plugins available on the internet such as ReCaptcha, aim of this tutorial is to share knowledge that how captcha works and how can we create our own custom captcha.

Requirement:

Please make sure that GD(Graphics Draw) library is installed on your host. Mostly web host already have it. But if you don’t then you can install it, follow instructions or ask you web hosting company to install it.

Steps to create a Captcha Using PHP

  1. Create an index.php file
  2. Create a captcha.php file

Create an index.php file

First of all I will create an index file, in this file I will create a html form of captcha. I will also add JavaScript that will refresh captcha without refreshing page. After captcha form submission, entered captcha code will be validated with the generated captcha code. If both are same user will see a message of success otherwise failure.

Now create index.php page and copy paste the below html captcha form in it.

HTML

Can't read the image?

click here

to refresh

JavaScript

Add the above JavaScript in the footer of index.php. This script will refresh the captcha if it is very difficult to read, so that user can insert new captcha code.

PHP Script

Enter the below php validation script in the header of index.php file, before starting the

tag.



Entered captcha code does not match! Kindly try again.

"; }else{ $status = "


Your captcha code is match.

"; } } echo $status; ?>

The above script is matching the captcha code with the users input and showing message of success or failure.

Create a captcha.php file

Now most important step, create a captcha.php file and copy paste the below script in it.

PHP Script



0xFF & ($integar >> 0x10), "green" => 0xFF & ($integar >> 0x8), "blue" => 0xFF & $integar); } ?>

In the above code, I include a font name monofont $captcha_font = ‘./monofont.ttf’; you can use any font that you want otherwise you can download this font from here.

Make sure that you keep this font in the same folder where you are keeping index.php and captcha.php files.

Now you can browse index.php file on your local host or online web host if you have. Our captcha form is now ready to use.

Explanation:

I have used comments to explain each step in the above code. However, I will also explain their working separately. captcha.php file is performing the following actions to create a captcha:

  • Creating a blank image with white background
  • Creating random dots
  • Creating random lines
  • Creating random 6 letters on image

Creating a blank image with white background

Following script is generating a blank image with height 50px and width 130px.


$captcha_image_height = 50; $captcha_image_width = 130; $captcha_image = @imagecreate( $captcha_image_width, $captcha_image_height ); $background_color = imagecolorallocate( $captcha_image, 255, 255, 255 ); header('Content-Type: image/jpeg'); imagejpeg($captcha_image);

Creating random dots

Following script is generating random dots in the image background.


$random_captcha_dots = 50; $captcha_noise_color = "0x142864"; $array_noise_color = hextorgb($captcha_noise_color); $image_noise_color = imagecolorallocate( $captcha_image, $array_noise_color['red'], $array_noise_color['green'], $array_noise_color['blue'] ); for( $count=0; $count<$random_captcha_dots; $count++ ) { imagefilledellipse( $captcha_image, mt_rand(0,$captcha_image_width), mt_rand(0,$captcha_image_height), 2, 3, $image_noise_color ); } function hextorgb ($hexstring){ $integar = hexdec($hexstring); return array("red" => 0xFF & ($integar >> 0x10), "green" => 0xFF & ($integar >> 0x8), "blue" => 0xFF & $integar); }

Creating random lines

Following script is generating random lines in the image background.


$random_captcha_lines = 25; for( $count=0; $count<$random_captcha_lines; $count++ ) { imageline( $captcha_image, mt_rand(0,$captcha_image_width), mt_rand(0,$captcha_image_height), mt_rand(0,$captcha_image_width), mt_rand(0,$captcha_image_height), $image_noise_color ); }

Creating random 6 letters on image

Following script is generating random 6 letters and putting them on the captcha image.


$captcha_code = ''; $total_characters_on_image = 6; $possible_captcha_letters = 'bcdfghjkmnpqrstvwxyz23456789'; $captcha_font = './monofont.ttf'; $captcha_text_color = "0x142864"; $count = 0; while ($count < $total_characters_on_image) { $captcha_code .= substr( $possible_captcha_letters, mt_rand(0, strlen($possible_captcha_letters)-1), 1); $count++; } $captcha_font_size = $captcha_image_height * 0.65; $array_text_color = hextorgb($captcha_text_color); $captcha_text_color = imagecolorallocate( $captcha_image, $array_text_color['red'], $array_text_color['green'], $array_text_color['blue'] ); $text_box = imagettfbbox( $captcha_font_size, 0, $captcha_font, $captcha_code ); $x = ($captcha_image_width - $text_box[4])/2; $y = ($captcha_image_height - $text_box[5])/2; imagettftext( $captcha_image, $captcha_font_size, 0, $x, $y, $captcha_text_color, $captcha_font, $captcha_code );

Always destroy the image instance after creating captcha image, using imagedestroy($captcha_image);

You may also noticed that I started session_start(); in the beginning of the page because I need to store a random generated captcha value in session variable $_SESSION[‘captcha’] = $captcha_code; to compare with the user input value for validation purpose.

If you found this tutorial helpful, kindly share it with your friends and developer groups.

Facebook Official Page: All PHP Tricks

Twitter Official Page: All PHP Tricks

phpTextCaptcha is an open-source, free PHP CAPTCHA script to create complex images and protect forms from spam and abuse.

Generate Captcha in PHP
Generate Captcha in PHP

PHP Captcha with Contact Form Example

This is one of the easiest and a simple PHP CAPTCHA Script example implemented with PHP form.

I have developed this project to give you the basic idea of how to get started with captcha to protect spam.

The project structure below can give you the ide of the thought process we are going to put in to stop spam using our free PHP captcha script.

We have a basic contact form with the name and email values that we will get from the site visitors.

We have set up a captcha field inside the form layout. The captcha is required and has the validation implemented on it.

It will be triggered when the user submits the form.


\-- php-demo |-- config |--- database.php |-- assets |--- css |--- style.css |-- scripts |--- captcha.php |--- contact_form.php |-- index.php

How to Make a CAPTCHA

We will use the PHP GD library to create a CAPTCHA. You can learn more about writing text and drawing shapes with GD in one of my earlier tutorials. We will also have to write a little bit of code to create our random string to be written on the image that’s created. Another tutorial, titled Generating Random Alphanumeric Strings in PHP, can help us in this regard.

  • Render Text and Shapes on Images in PHPMonty Shokeen20 May 2022
  • Generate Random Alphanumeric Strings in PHPMonty Shokeen23 Nov 2020

Generate a Random String

All the code from this section will go in the captcha.php file. Let’s begin by writing the function to create the random string.

$permitted_chars = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’;

function generate_string($input, $strength = 5) {

$input_length = strlen($input);

$random_string = ”;

for($i = 0; $i < $strength; $i++) {

$random_character = $input[mt_rand(0, $input_length – 1)];

10

$random_string .= $random_character;

11

12

13

return $random_string;

14

15

16

$string_length = 6;

17

$captcha_string = generate_string($permitted_chars, $string_length);

18

19

20

?>

The

$permitted_chars

variable stores all the characters that we want to use to generate our CAPTCHA string. We are only using capital letters in the English alphabet to avoid any confusion that might arise due to letters or numbers that might look alike. You can use any set of characters that you like to increase or decrease the difficulty of the CAPTCHA.

Our function creates a five-letter string by default, but you can change that value by passing a different parameter to the

generate_string()

function.

Generate a Cryptographically Secure Random String

You can use cryptographically secure functions to generate random strings and make the CAPTCHA PHP form harder to guess.

In this particular case, we can use the

random_int()

function in place of

mt_rand()

. It accepts the same two parameters but generates cryptographically secure random numbers. Here is our modified code for generating the random strings.

$permitted_chars = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’;

function secure_generate_string($input, $strength = 5, $secure = true) {

$input_length = strlen($input);

$random_string = ”;

for($i = 0; $i < $strength; $i++) {

if($secure) {

10

$random_character = $input[random_int(0, $input_length – 1)];

11

} else {

12

$random_character = $input[mt_rand(0, $input_length – 1)];

13

14

$random_string .= $random_character;

15

16

17

return $random_string;

18

19

20

$string_length = 6;

21

$captcha_string = secure_generate_string($permitted_chars, $string_length);

22

23

24

?>

The only change we make here is the use of a third parameter in our

generate_string()

function. This third parameter called

$secure

is set to

true

by default. Later in the code, we check if

$secure

is set to

true

and then use

random_int()

to generate the string.

Modifying our function this way allows us to make the output of all our previous calls of the function cryptographically secure without making any changes to old code. It also allows us to generate random strings which are not cryptographically secure by explicitly setting the third parameter to

false

in any future calls.

How to Make a CAPTCHA Background

Once we have our random string, it’s time to write the code to create a CAPTCHA image of our background. The CAPTCHA image background will be 200 x 50 pixels in size and will use five different colors for the background.

$image = imagecreatetruecolor(200, 50);

imageantialias($image, true);

$colors = [];

$red = rand(125, 175);

10

$green = rand(125, 175);

11

$blue = rand(125, 175);

12

13

for($i = 0; $i < 5; $i++) {

14

$colors[] = imagecolorallocate($image, $red – 20*$i, $green – 20*$i, $blue – 20*$i);

15

16

17

imagefill($image, 0, 0, $colors[0]);

18

19

for($i = 0; $i < 10; $i++) {

20

imagesetthickness($image, rand(2, 10));

21

$rect_color = $colors[rand(1, 4)];

22

imagerectangle($image, rand(-10, 190), rand(-10, 10), rand(-10, 190), rand(40, 60), $rect_color);

23

24

25

?>

We begin with random values for the variables

$red

,

$green

, and

$blue

. These values determine the final color of the CAPTCHA image background. After that, we run a

for

loop to create progressively darker shades of the original color. These colors are stored in an array. The lightest color is the first element of our

$colors

array, and the darkest color is the last element. The lightest color is used to fill the whole background of the image.

In the next step, we use a

for

loop to draw rectangles at random locations on our original image. The thickness of the rectangles varies between 2 and 10, while the color is chosen randomly from the last four values of our

$colors

array.

Drawing all these rectangles adds more colors to the background, making it a little harder to distinguish the foreground of the CAPTCHA string from the background of the image.

Your CAPTCHA picture background should now look similar to the following CAPTCHA image.

Here’s a CAPTCHA PHP example of the background:

Render the CAPTCHA String

For the final step, we just have to draw the CAPTCHA string on our background. The color, y-coordinate, and rotation of individual letters is determined randomly to make the CAPTCHA string harder to read.

$black = imagecolorallocate($image, 0, 0, 0);

$white = imagecolorallocate($image, 255, 255, 255);

$textcolors = [$black, $white];

$fonts = [dirname(__FILE__).’\fonts\Acme.ttf’, dirname(__FILE__).’\fonts\Ubuntu.ttf’, dirname(__FILE__).’\fonts\Merriweather.ttf’, dirname(__FILE__).’\fonts\PlayfairDisplay.ttf’];

$string_length = 6;

10

$captcha_string = secure_generate_string($permitted_chars, $string_length);

11

12

for($i = 0; $i < $string_length; $i++) {

13

$letter_space = 170/$string_length;

14

$initial = 15;

15

16

imagettftext($image, 20, rand(-15, 15), $initial + $i*$letter_space, rand(20, 40), $textcolors[rand(0, 1)], $fonts[array_rand($fonts)], $captcha_string[$i]);

17

18

19

header(‘Content-type: image/png’);

20

imagepng($image);

21

imagedestroy($image);

22

23

?>

As you can see, I’m using some fonts I downloaded from Google to get some variation in the characters. There is a padding of 15 pixels on both sides of the image. The leftover space—170 pixels—is divided equally among all the PHP form CAPTCHA letters.

After rendering the text string above the background, your result should look similar to the image below. The characters will be different, but they should be slightly rotated and a mix of black and white.

Here’s a CAPTCHA PHP example of the background and the letters:

Integrate Google reCAPTCHA v3 in HTML Form with PHP
Integrate Google reCAPTCHA v3 in HTML Form with PHP

phptextClass.php

Main class file with phpcaptcha, hexToRGB and ImageTTFCenter function.



random(); $font = './font/monofont.ttf';/* font */ $textColor=$this->hexToRGB($textColor); $fontSize = $imgHeight * 0.75; $im = imagecreatetruecolor($imgWidth, $imgHeight); $textColor = imagecolorallocate($im, $textColor['r'],$textColor['g'],$textColor['b']); $backgroundColor = $this->hexToRGB($backgroundColor); $backgroundColor = imagecolorallocate($im, $backgroundColor['r'],$backgroundColor['g'],$backgroundColor['b']); /* generating lines randomly in background of image */ if($noiceLines>0){ $noiceColor=$this->hexToRGB($noiceColor); $noiceColor = imagecolorallocate($im, $noiceColor['r'],$noiceColor['g'],$noiceColor['b']); for( $i=0; $i<$noiceLines; $i++ ) { imageline($im, mt_rand(0,$imgWidth), mt_rand(0,$imgHeight), mt_rand(0,$imgWidth), mt_rand(0,$imgHeight), $noiceColor); }} if($noiceDots>0){/* generating the dots randomly in background */ for( $i=0; $i<$noiceDots; $i++ ) { imagefilledellipse($im, mt_rand(0,$imgWidth), mt_rand(0,$imgHeight), 3, 3, $textColor); }} imagefill($im,0,0,$backgroundColor); list($x, $y) = $this->ImageTTFCenter($im, $text, $font, $fontSize); imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $text); imagejpeg($im,NULL,90);/* Showing image */ header('Content-Type: image/jpeg');/* defining the image type to be shown in browser widow */ imagedestroy($im);/* Destroying image instance */ if(isset($_SESSION)){ $_SESSION['captcha_code'] = $text;/* set random text in session for captcha validation*/ } } /*function to convert hex value to rgb array*/ protected function hexToRGB($colour) { if ( $colour[0] == '#' ) { $colour = substr( $colour, 1 ); } if ( strlen( $colour ) == 6 ) { list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] ); } elseif ( strlen( $colour ) == 3 ) { list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] ); } else { return false; } $r = hexdec( $r ); $g = hexdec( $g ); $b = hexdec( $b ); return array( 'r' => $r, 'g' => $g, 'b' => $b ); } /*function to get center position on image*/ protected function ImageTTFCenter($image, $text, $font, $size, $angle = 8) { $xi = imagesx($image); $yi = imagesy($image); $box = imagettfbbox($size, $angle, $font, $text); $xr = abs(max($box[2], $box[4]))+5; $yr = abs(max($box[5], $box[7])); $x = intval(($xi - $xr) / 2); $y = intval(($yi + $yr) / 2); return array($x, $y); } } ?>

Final Thoughts on the Form with CAPTCHA

In this tutorial, we created our custom CAPTCHA in PHP from scratch and integrated it with a PHP contact form we built in one of our earlier tutorials. We also made the form with CAPTCHA more user-friendly by adding a refresh button so that users get a new string with a new background in case the previous one was unreadable.

You can also use the logic from this tutorial to create a CAPTCHA picture that relies on solving basic mathematical equations like addition and subtraction.

If you want to add a CAPTCHA picture to your website, you should check out some of the form and CAPTCHA plugins available from CodeCanyon. Some of these have CAPTCHA and many other features like a file uploader built in.

  • 18 Best Contact Form PHP Scripts for 2023Monty Shokeen11 May 2022
  • Comparing the 5 Best PHP Form Builders (And 3 Free Scripts)Monty Shokeen28 Nov 2021
  • 19 PHP Login and Registration Forms to DownloadDaniel Stern15 Aug 2021

If you have any questions or suggestions, feel free to let me know in the comments. You should also take a look at this list of the best PHP contact forms.

  • 18 Best Contact Form PHP Scripts for 2023Monty Shokeen11 May 2022
  • Create a Contact Form in PHPMonty Shokeen15 Apr 2021

Editorial Note: This post has been updated with contributions from Gonzalo Angulo. Gonzalo is a staff writer with Envato Tuts+.

  • shares
  • Facebook Messenger
  • Gmail
  • Viber
  • Skype

Trong bài viết này mình sẽ hướng dẫn các bạn cách tạo captcha trong PHP sử dụng thư viện simple-php-captcha.Tải thư viện tạo captcha dễ dàng với PHP của claviska tại đây.

Kiểm tra hỗ trợ PHP GD2

Thư viên yêu cầu có hỗ trợ PHP GD2. Đảm bảo thư viện này có cài đặt trên web server. Bằng cách tạo file kiểm tra test.php và up lên thư mục gốc của website.

Truy cập test.php trên trình duyệt. ie: http://www.yoursite.com/test.phpHàm trên sẽ hiển thị toàn bộ thông tin cài đặt PHP trên web server của bạn. Cuộn xuống dưới nếu hình thấy như hình dưới đây, nghĩa là PHP GD đã kích hoạt.

Cách khác để kiểm tra PHP GD trên web server thông qua sử dụng hàm, nếu PHP GD đã cài đặt và sẵn sàng sử dụng thì bạn sẽ có thêm hàm

gd_info

. Bằng cách kiểm tra hàm này có tồn tại không là biết ngay.

Sử dụng captcha mặc định

Để tạo ảnh captcha chúng ta gọi hàm

simple_php_captcha()

. Chèn thư viện

simple-php-captcha.php

trước khi sử dụng.

Sau khi gọi, hàm trả mảng chứa mã số và URL ảnh tương ứng với mã số đó. Chúng ta cần lưu thông tin này vào biến SESSION để so sánh sau khi người dùng nhấn submit form.

Array ( => hu5sF [image_src] => /simple-php-captcha/simple-php-captcha.php?_CAPTCHA&t=0.93480200+1413380000 )

Để hiển thị ảnh Captcha, bạn tạo thẻ img và chèn link ảnh vào thuộc tính ‘src’ lấy từ biến

$_SESSION['captcha']['image_src']

.

Tại code lấy dữ liệu form để sử lý lưu vào dữ liệu, trước đó bạn sẽ kiểm tra giá trị ‘code’ $_SESSION[‘captcha’][‘code’] có khớp với trường nhập captcha của người dùng không. Nếu không đúng thì dừng chạy đoạn code sử lý chính.Bạn có thể yêu cầu nhập đúng chữ hoa nếu có trong ký tự captcha hoặc không cần sử dùng 2 hàm trong khi so sánh

strtolower()

,

strtoupper()

. Ví dụ:

if(isset($_POST[‘submit’])){ if(strtolower($_SESSION[‘captcha’][‘code’])==strtolower($_POST[‘captcha’])){ } }

Tùy biến nâng cao

Các tham số có thể sử dụng, cấu hình cho captcha được truyền vào hàm

simple_php_captcha

. Sử dụng một số các tùy chọn sau:


5, ‘max_length’ => 5, ‘backgrounds’ => array(image.png’, …), ‘fonts’ => array(‘font.ttf’, …), ‘characters’ => ‘ABCDEFGHJKLMNPRSTUVWXYZabcdefghjkmnprstuvwxyz23456789’, ‘min_font_size’ => 28, ‘max_font_size’ => 28, ‘color’ => ‘#666’, ‘angle_min’ => 0, ‘angle_max’ => 10, ‘shadow’ => true, ‘shadow_color’ => ‘#fff’, ‘shadow_offset_x’ => -1, ‘shadow_offset_y’ => 1 )); ?>

Giải thích:


  • min_length, max_length

    : số ký tự trong hình captcha sẽ giao động ngẫu nhiên từ min_length đến max_length. Bạn có thể fix cố định lượng chữ cái bằng cách thiết lập một số chung cho 2 giá trị này, vd như trên.

  • backgrounds

    : hình nền cho captcha, cũng là để xác định kích thước ảnh, khai báo danh sách các hình nền với định dạng duy nhất .PNG. Captcha sinh ra sẽ lấy hình ngẫu nhiên trong số hình bạn liệt kê và kích thước của hình nền chính là kích thước của captcha. Chú ý: đường dẫn tới file ảnh dưới dạng tường minh (absolute). ie:

    $_SERVER['DOCUMENT_ROOT'] . '/' . [path-to-file]

  • fonts

    : font chữ hiển thị cho captcha, cũng giống như ‘backgrounds’, những lần load trang captcha sẽ tạo với nhiều fonts khác nhau, nếu bạn liệt kê nhiều fonts .TTF hoặc .OTF vào đây. Sử dụng absolute path tới file font như backgrounds.

  • characters

    : liệt kê các chữ cái được phép sử dụng tạo hình captcha.

  • min_font_size, max_font_size

    : những chữ cái trong hình captcha có thể hiển thị với nhiều kích thước font khác nhau. Font nhỏ nhất là ‘min_font_size’ và lớn nhất là ‘max_font_size’ các chữ cái tạo size ngẫu nhiên trong khoảng này. Lưu ý: điều chỉnh thông số này cho phù hợp tương ứng với kích thước của backgrounds, tránh font tràn ngoài vùng backgrounds.

  • color

    : mẫu chữ cái của captcha.

  • angle_min, angle_max

    : độ nghiêng toàn bộ chữ cái của captcha trong hình. Giá trị này không nên lớn hơn 15, captcha có thể hiển thị bên ngoài vùng backgrounds. Tuy nhiên bạn sẽ phải thiết lập giá trị này một con số từ [0-15] điều cho phù hợp với kích thước các backgrounds. Nếu bạn dùng nhiều backgrounds thì nên cùng kích thước.

  • shadow, shadow_color, shadow_offset_x, shadow_offset_y

    : thiết lập độ bóng cho text.

VD: tạo captcha hiển thị khác với mặc định:

Nếu bạn thích bài viết này, hãy ủng hộ chúng tôi bằng cách đăng ký nhận bài viết mới ở bên dưới và đừng quên chia sẻ kiến thức này với bạn bè của bạn nhé. Bạn cũng có thể theo dõi blog này trên Twitter và Facebook

  • shares
  • Facebook Messenger
  • Gmail
  • Viber
  • Skype
simple captcha code in php using javascript !! captcha script in php using java script
simple captcha code in php using javascript !! captcha script in php using java script

HTML




php


session_start();


msg


''


// If user has given a captcha!


if (isset($_POST['input']) && sizeof($_POST['input']) > 0)


// If the captcha is valid


if ($_POST['input'] == $_SESSION['captcha'])


$msg = '<


span


style


"color:green"


>SUCCESSFUL!!!


span


>';


else


$msg = '<


span


style


"color:red"


>CAPTCHA FAILED!!!


span


>';


?>


style


body{


display:flex;


flex-direction:column;


align-items: center;


justify-content: center;




style


body


h2


>PROVE THAT YOU ARE NOT A ROBOT!!


h2


strong


Type the text in the image to prove


you are not a robot




strong


div


style


'margin:15px'


img


src


"captcha.php"




div


form


method


"POST"


action=


"

">


input


type


"text"


name


"input"


/>


input


type


"hidden"


name


"flag"


value


"1"


/>


input


type


"submit"


value


"Submit"


name


"submit"


/>




form


div


style


'margin-bottom:5px'




php


echo $msg; ?>




div


div


Can't read the image? Click


href


'


PHP_SELF']; ?>'>


here




to refresh!




div




body

Even though Captchas may be very annoying yet without Captchas we might not know the Internet as we do know. Captchas are essential for fighting spam and keeping the web alive.

Do not use this script in production code: The main issue with our image captcha is that any experienced programmer can easily create a bot that can process the images and extract the text and send a POST request and verify itself as a human. To tackle this issue we can perhaps add random lines, dots (unit-length circles), etc in the foreground but image processing has developed to the extent that it would only make it a little difficult for the programmer to process the image and stringify it.So the best solution is to use a specialized and well-tested library like Google’s reCAPTCHA which is both easy to integrate in your PHP environment and also somewhat less “pain in the neck” compared to those traditional “type the text” since it can sometimes not generate a captcha at all if it already knows the user is not a bot based on his previous activities.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!

Last Updated :
05 Oct, 2021

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Note: This tutorial was originally written 10 years ago. It has now been updated with entirely new code for generating a random string. Many of the comments in the discussion thread reference the original version of the code.

People write code every day to automate a variety of processes. We exploit the fact that computers are a lot faster and more accurate than humans, which lets us simplify a lot of mundane tasks. Unfortunately, these same abilities can be used to program computers to do something malicious like sending spam or guessing passwords. The focus of this tutorial will be on combating spam.

Let’s say you have a website with a contact form to make it easy for visitors to contact you. All they have to do is fill out a form and hit the send button to let you know about a problem or request they have. This is an important feature of a public-facing website, but the process of filling out form values can be automated by malicious users to send a lot of spam your way. This type of spamming technique is not limited to contact forms. Bots can also be used to fill your forums with spam posts or comments that link to harmful websites.

One way to solve this problem is to devise a test which can distinguish between bots which are trying to spread spam and people who legitimately want to contact you. This is when a CAPTCHA and PHP form come in. They generally consist of images with a random combination of five or six letters written on a colored background. The idea is that a human will be able to read the text inside the image, but a bot won’t. Checking the user-filled CAPTCHA image value against the original can help you distinguish bots from humans. CAPTCHA stands for “completely automated public Turing test to tell computers and humans apart”.

In this tutorial, we will learn how to create our own CAPTCHAs and then integrate them with the contact form we created in the tutorial.

Keywords searched by users: captcha code in php

Simple Captcha System In Php + Source Code | Real Time Image Creation |  Quick Programming Tutorial - Youtube
Simple Captcha System In Php + Source Code | Real Time Image Creation | Quick Programming Tutorial – Youtube
How To Implement Custom Captcha In Php - Youtube
How To Implement Custom Captcha In Php – Youtube
How To Generate Captcha Image In Php ? - Geeksforgeeks
How To Generate Captcha Image In Php ? – Geeksforgeeks
Php Captcha - Phppot
Php Captcha – Phppot
Create A Simple Captcha Script Using Php | All Php Tricks
Create A Simple Captcha Script Using Php | All Php Tricks
Make Captcha Script In Php With Ajax | Webslesson
Make Captcha Script In Php With Ajax | Webslesson
Github - Captcha-Com/Laravel-Captcha: Botdetect Php Captcha Generator  Integration For The Laravel Framework.
Github – Captcha-Com/Laravel-Captcha: Botdetect Php Captcha Generator Integration For The Laravel Framework.
Creating A Simple Captcha Generator In Php Tutorial | Sourcecodester
Creating A Simple Captcha Generator In Php Tutorial | Sourcecodester
Php - Simple Login With Captcha | Sourcecodester
Php – Simple Login With Captcha | Sourcecodester
Dcoding English | Simple Captcha Code Using Php
Dcoding English | Simple Captcha Code Using Php
How To Integrate Google Recaptcha With Php Form? - Itsolutionstuff.Com
How To Integrate Google Recaptcha With Php Form? – Itsolutionstuff.Com

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *