Receive JSON POST Data

From Michael's Information Zone
Jump to navigation Jump to search

Purpose

Request came across my desk for a web server to receive JSON POST data, providing web hooks for another system to parse. On my end things were simple enough.

  1. Simple Apache server to receive requests.
  2. Basic Authentication
  3. Save the POST data to file (For now, but I feel this will be expanded in the near future)

Process

Apache Config

Very simple and clean vhost.

<VirtualHost *:80>
DocumentRoot /var/www/html/
<Directory /var/www/html/>
AuthType Basic
AuthName "Restricted"
AuthBasicProvider file
AuthUserFile "/etc/httpd/password"
Require valid-user
</Directory>
</VirtualHost>

Quick and dirty password file

htpasswd -bc /etc/httpd/password test test

PHP Script

[1][2]This example will echo the posted data back to the client during testing, as well as save the file to disk.

<?php
$myFile = "testFile.txt";
$data = file_get_contents('php://input');
echo $data;
file_put_contents($myFile,$data);
?>

To further build on this, and to keep track of the received hooks, I wanted to add a date/time stamp to the file[3].

<?php
$today = date("mdY_His");
$myFile = "testFile_$today.txt";
$data = file_get_contents('php://input');
file_put_contents($myFile,$data);
?>

Testing

Used the following POST method with curl to test with.

curl -X POST -H "Content-Type: application/json" --data '{"test":"1"}' http://localhost

Again, but with a username/password

curl --user test:test -X POST -H "Content-Type: application/json" --data '{"test":"1"}' http://localhost