File: //home/jibhires/d1.brightsolutionsindia.com/testapi.php
<?php
require_once __DIR__ . '/config.php';
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("X-Content-Type-Options: nosniff");
// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Max-Age: 3600");
exit(0);
}
try {
// Validate request method
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
throw new Exception("Method Not Allowed", 405);
}
// Validate API key
$api_key = $_POST['api_key'] ?? '';
if (!hash_equals(API_KEY_VALUE, $api_key)) {
throw new Exception("Unauthorized", 401);
}
// Validate required fields
$required = ['dev_id', 'loc_temp', 'loc_hum'];
foreach ($required as $field) {
if (empty($_POST[$field])) {
throw new Exception("Missing field: $field", 400);
}
}
// Sanitize inputs
$dev_id = substr(trim($_POST['dev_id']), 0, 30);
$temp = filter_var($_POST['loc_temp'], FILTER_VALIDATE_FLOAT);
$hum = filter_var($_POST['loc_hum'], FILTER_VALIDATE_FLOAT);
// Validate values
if ($temp === false || $hum === false) {
throw new Exception("Invalid sensor values", 400);
}
if ($temp < -50 || $temp > 150 || $hum < 0 || $hum > 100) {
throw new Exception("Values out of range", 400);
}
// Database connection
$conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
throw new Exception("Database connection failed", 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()) {
error_log("Database Error: " . $stmt->error);
throw new Exception("Data recording failed", 500);
}
echo json_encode([
'status' => 'success',
'id' => $stmt->insert_id,
'timestamp' => date('Y-m-d H:i:s')
]);
$stmt->close();
$conn->close();
} catch (Exception $e) {
http_response_code($e->getCode() ?: 500);
echo json_encode([
'status' => 'error',
'error' => $e->getMessage(),
'code' => $e->getCode()
]);
}