Trouble with PHP processing POST data from IoT device

I’m new to web dev and stuck on a basic project. I’ve got a Particle Photon board sending JSON data via POST to my Apache server whenever an event happens. I want to use PHP to handle this data and update what the user sees.

Here’s my current index.php:

<html>
<body>
  <div>
    <?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
      $input = file_get_contents('php://input');
      $data = json_decode($input);
      // process $data here
    }
    ?>
  </div>
</body>
</html>

But it’s not working. When I try to echo or var_dump, I get nothing or NULL. Am I missing something? The webhook seems to be sending data correctly. I’m not worried about security right now, just want to get it working.

The JSON looks like this:

{
  "event": "my_event",
  "data": "42",
  "published_at": "2023-05-15T10:30:00Z",
  "coreid": "abc123"
}

Any ideas what I’m doing wrong? This is the only file on my server.

hey there! using var_dump($_POST) might help reveal the incoming data. also, have you checked apache error logs for any clues?

i’m curious, what event info is comin in from your photon?

yo dude, i think ur prob might be with the content type. try addin this at the top of ur php:

header(‘Content-Type: application/json’);

then use json_decode(file_get_contents(‘php://input’), true);

that should grab the raw post data. let me kno if it works!

Your approach is on the right track, but there’s a key issue to address. When receiving JSON data via POST, PHP doesn’t automatically populate the $_POST superglobal. Instead, you need to directly access the raw input stream.

Try modifying your code like this:

<?php
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if ($data !== null) {
    // Process $data here
    $event = $data['event'];
    $value = $data['data'];
    // Use the data as needed
} else {
    // Handle JSON parsing error
    error_log('Failed to parse JSON: ' . json_last_error_msg());
}
?>

<html>
<body>
  <div>
    <!-- Display processed data here -->
  </div>
</body>
</html>

This approach should correctly capture and parse the JSON data from your IoT device. Remember to implement proper error handling and security measures as you develop further.