PHP

PHP 캡챠 연동

생활개발 2024. 5. 30. 16:58
728x90

 

 

https://www.google.com/recaptcha/admin/create 접속

 

1. V3 AdminConsole 클릭

2. 값 입력

 

 

위 화면이 안나올 경우 Switch to create a legacy key 클릭

라벨: 프로젝트의 이름을 입력합니다. 예를 들어, "My Website reCAPTCHA".

reCAPTCHA 유형: 사용할 유형을 선택합니다

reCAPTCHA v2: 사용자가 로봇이 아님을 증명하기 위해 체크박스를 클릭합니다.

  • "로봇이 아닙니다.”체크박스: 체크박스를 표시합니다. “로봇이 아닙니다.”                                                                             체크박스를 사용하여 요청을 확인합니다.
  • 표시되지 않는 reCAPTCHA배지: 사용자가 클릭할 필요 없이 작동합니다,                                                                                백그라운드에서 요청을 확인합니다.
  • reCAPTCHA Android: Android 앱에서 사용합니다.

reCAPTCHA v3: 사용자에게 보이지 않고 점수를 기반으로 동작합니다.

도메인: reCAPTCHA를 사용할 도메인을 입력합니다. 예를 들어, "example.com". 여러 도메인을 추가할 수 있습니다.

소유자: 기본적으로 현재 로그인된 Google 계정이 추가됩니다. 다른 이메일 주소를 추가할 수 있습니다.

reCAPTCHA 서비스 약관에 동의해 주세요.: 약관에 동의합니다.

 

 

테스트하기 

captcha.php

<?
$sitekey = '발급받은 사이트키';
$secretKey = "발급받은 시크릿키";

include_once 'captchaCheck.php';
?>

<html>
    <head>
        <title>Google recapcha Test</title>
        <script src='https://www.google.com/recaptcha/api.js'></script>
    </head>

    <body>
        <h1>Google reCAPTHA Test</h1>
        <form action="" method="post">
            <input type="text" name="name" size="40"><br><br>
            <textarea name="contents" rows="8" cols="40"></textarea><br><br>
            <input type="submit" name="submit" value="Submit"><br><br>
            <div class="g-recaptcha" data-sitekey="<?php echo $sitekey; ?>"></div>
        </form>
    </body>
</html>

 

captchaCheck.php 코드

<?php

if($_SERVER['REQUEST_METHOD'] === "POST") {
    $name = null;
    $contents = null;

    if($_POST['name']){
        $name = $_POST['name'];
    }
    if($_POST['contents']){
        $contents = $_POST['contents'];
    }

    $responseKey = $_POST['g-recaptcha-response'];
    $userIP = $_SERVER['REMOTE_ADDR'];

    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $data = array(
        'secret' => $secretKey,
        'response' => $responseKey,
        'remoteip' => $userIP
    );

    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data),
        ),
    );

    $context  = stream_context_create($options);
    $response = file_get_contents($url, false, $context);
    $result = json_decode($response);

    //체크 확인
    if ($result->success) { //체크
        echo "name = $name <br />";

        echo "contents = $contents <br />";
        die();
    } else { //미체크
        echo "로봇이 아니면 체크해주세요.";
        die();
    }
}
?>

 

완료 화면

 

미체크 제출시

체크 제출시

 

728x90