Contact Form PHP Action to Discord Webhook?

Viewed 318

I was following a tutorial on Youtube but I never could get the webhook to work

Here is what my html & php code looks like, also here is a link incase you want to look at it https://chsn.me/leaveamessage.html

Leave a Message HTML

    <div class="container-contact">
          <h2>Leave a message</h2>
    </div>
          <div class="column">
            <form action="/action_page.php">
              <label for="username">Discord</label>
              <input type="text" id="username" name="username" placeholder="(include the # with numbers & usernames are case sensitive)" required>              
              <label for="game">Service</label>
              <select id="game" name="game">
                <option value="cod">Call of Duty</option>
                <option value="forza">Forza</option>
                <option value="other">Other</option>
              </select>
              <label for="subject">Subject</label>
              <textarea id="subject" name="subject" placeholder="Write something.." style="height:170px"></textarea>
              <input type="submit" value="submit">
            </form>
          </div>

Action PHP File

<?php

        
    $url = "DISCORD WEBHOOK LINK HERE";
    $headers = [ 'Content-Type: application/json; charset=utf-8' ];
    $POST = [ 'name' => '$username','game' => '$service', 'subject' => '$subject'];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($POST));
    $response   = curl_exec($ch);

    
    header("Location: messagesuccess.html");

?>
2 Answers

Correct code for my specific setup

<?php

$me = "Discord: ".$_POST['username' ].
        " Service: ".$_POST['game'].
            " Message: ".$_POST['subject'];
    $data = ['content' => $me];
    $options = [
        'http' => [
            'method' => 'POST', 
            'header' => 'Content-Type: application/json',
            'content' => json_encode($data)
        ]
    ];

    $context = stream_context_create($options);
    $result = file_get_contents('DISCORD WEBHOOK LINK HERE', false, $context);

    header("Location: messagesuccess.html");
?>

There is better way to do this. Step 1. Create new table in the database called "messages" and create 3 columns 1-id 2-from 3-service Step 2. Code the action php file to insert the post data into the database Step 3. Make another page where you will echo the values from the messages table and boom thats it. Hope it helped!

Related