Developers Diary

Webhook JSON

Featured Post Image - Webhook JSON

At work I am writing code to run after a 3rd party forms vendor submits a user’s form. The form submission data is in JSON format. Today I learned about file_get_contents(‘php://input’); This is the command I used to read in the contents of the form submission, and then used the json_decode functionality to put it into a PHP object. Once it’s in PHP I can work with it easily to email the contents to myself.

 ob_start();
error_reporting(E_ALL); ini_set('display_errors', 1);
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    header("Location: https://xxx.com");
    die;
}

//we have php://input that is a read-only stream with the raw body of a POST request. This is handy when we’re dealing with remote services that put data payloads inside the body of a POST request.
$json = file_get_contents("php://input");

// Decode JSON data to PHP associative array
$arr = json_decode($json, true);

//get the contents of the submitted form from the array
$first_name = $arr["first"];
$email = $arr["Email"];
$thelocation = $arr["Location"];
$mywebsite = $arr["mywebsite"];

//If wordpress isn't loaded load it up so we can use WP functions & way of doing things
if ( !defined('ABSPATH') ) {
    $path = $_SERVER['DOCUMENT_ROOT'];
    include_once $path . '/wp-load.php';
}
//write form submission contents to a dump txt file:
//URL - can't reference URL to write file, use the syntax the server understands:
$url = "/srv/bindings/xxxxxxxxx/files/sandy/sandydump.txt";
$myfile = fopen($url, "a") or die("Unable to open file!");
$txt = $first_name."-".$email."-".$thelocation."-".$mywebsite;
fwrite($myfile, $txt);
fclose($myfile);


//testing wp mailer function, just because.
$to = "sandyxxx@xxxxx.com";
$subject = "Webhook test";
$message = $first_name."-".$email."-".$thelocation."-".$mywebsite;
$headers = '';
wp_mail($to, $subject, $message, $headers )