MOON
Server: Apache
System: Linux server30c.hostingraja.org 3.10.0-962.3.2.lve1.5.63.el7.x86_64 #1 SMP Fri Oct 8 12:03:35 UTC 2021 x86_64
User: jibhires (1887)
PHP: 8.1.30
Disabled: show_source, system, shell_exec, passthru, exec, popen, proc_open, allow_url_fopen, symlink, escapeshellcmd, pcntl_exec
Upload Files
File: //home/jibhires/www/skdf87api.php
<?php
require_once __DIR__ . '/d1config.php';

// Set headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("X-Content-Type-Options: nosniff");

// Handle preflight request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header("Access-Control-Allow-Methods: POST");
    header("Access-Control-Allow-Headers: Content-Type");
    exit(0);
}

try {
    if ($_SERVER["REQUEST_METHOD"] !== "POST") {
        throw new Exception("Only POST requests allowed", 405);
    }

    // Validate API Key
    $api_key = $_POST['api_key'] ?? '';
    if (!hash_equals(API_KEY_VALUE, $api_key)) {
        throw new Exception("Unauthorized access", 401);
    }

    // Validate required fields
    $required = ['dev_id', 'loc_temp', 'loc_hum'];
    foreach ($required as $field) {
        if (!isset($_POST[$field]) || $_POST[$field] === '') {
            throw new Exception("Missing required field: $field", 400);
        }
    }

    // Sanitize inputs
    $dev_id = substr(trim($_POST['dev_id']), 0, 30);
    $temp = (float)$_POST['loc_temp'];
    $hum = (float)$_POST['loc_hum'];

    // Validate ranges
    if ($temp < -50 || $temp > 150 || $hum < 0 || $hum > 100) {
        throw new Exception("Invalid sensor values", 400);
    }

    // Database connection
    $conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
    if ($conn->connect_error) {
        throw new Exception("Database connection failed: " . $conn->connect_error, 500);
    }

    // Prepared statement
    $stmt = $conn->prepare("INSERT INTO hum_temp_data (dev_id, loc_temp, loc_hum) VALUES (?, ?, ?)");
    $stmt->bind_param("sdd", $dev_id, $temp, $hum);

    if (!$stmt->execute()) {
        throw new Exception("Database error: " . $stmt->error, 500);
    }

    echo json_encode([
        'status' => 'success',
        'id' => $stmt->insert_id,
        'message' => 'Data recorded successfully'
    ]);

    $stmt->close();
    $conn->close();

} catch (Exception $e) {
    http_response_code($e->getCode() ?: 500);
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage(),
        'code' => $e->getCode()
    ]);
}