• March 11, 2023

    use Cloudflare Turnstile to protect a form-to-email script in JavaScript:

    index.html

    <!DOCTYPE html>
    <html>
    <head>
      <title>Contact Form</title>
    </head>
    <body>
      <h1>Contact Us</h1>
      <form action="send-email.php" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required><br>
        <label for="message">Message:</label><br>
        <textarea id="message" name="message" required></textarea><br>
        <button type="submit">Send Message</button>
      </form>
    </body>
    </html>
    
    

    send-email.php

    <?php
    require_once __DIR__ . '/vendor/autoload.php';
    
    use Cloudflare\Turnstile\Turnstile;
    
    $turnstile = new Turnstile(['max' => 10, 'interval' => 1, 'whitelist' => ['1.2.3.4']]);
    
    $request = new \GuzzleHttp\Psr7\ServerRequest('POST', '', $_SERVER);
    $result = $turnstile->take($request);
    if ($result->getStatus() === 'pass') {
      if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['CONTENT_TYPE'] === 'application/x-www-form-urlencoded') {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
        $subject = 'New message from ' . $name;
        $body = "Name: $name\nEmail: $email\nMessage: $message";
        $recipients = ['youremail@example.com'];
        $sendResult = sendEmail($subject, $body, $recipients);
        if ($sendResult->getStatusCode() === 200) {
          echo 'Thanks for your message!';
        } else {
          http_response_code(500);
          echo 'Error sending message';
        }
      } else {
        http_response_code(400);
        echo 'Invalid request';
      }
    } else {
      http_response_code(401);
      echo 'Unauthorized';
    }
    
    function sendEmail($subject, $body, $recipients) {
      $client = new GuzzleHttp\Client();
      $url = 'https://api.example.com/send-email';
      $payload = ['subject' => $subject, 'body' => $body, 'recipients' => $recipients];
      $response = $client->post($url, [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode($payload)
      ]);
      return $response;
    }
    


เวอไนน์ไอคอร์ส

ประหยัดเวลากว่า 100 เท่า!






เวอไนน์เว็บไซต์⚡️
สร้างเว็บไซต์ ดูแลเว็บไซต์

Categories


Uncategorized