File: //home/jibhires/d1.brightsolutionsindia.com/gfjs6545dklls.php
<?php
require_once(__DIR__) . '/d1config.php';
header("Content-Type: application/json");
if ($_SERVER["REQUEST_METHOD"] != "POST") {
http_response_code(405);
die(json_encode(["error" => "Method not allowed"]));
}
// Validate API Key
$api_key = $_POST["api_key"] ?? '';
if (!hash_equals(API_KEY_VALUE, $api_key)) {
http_response_code(401);
die(json_encode(["error" => "Unauthorized"]));
}
// Validate Inputs
$required = ['dev_id', 'loc_temp', 'loc_hum'];
foreach ($required as $field) {
if (empty($_POST[$field])) {
http_response_code(400);
die(json_encode(["error" => "Missing $field"]));
}
}
// Sanitize and Validate Data
$dev_id = substr($_POST["dev_id"], 0, 30); // Match VARCHAR(30)
$temp = (float)$_POST["loc_temp"];
$hum = (float)$_POST["loc_hum"];
// Validate Number Ranges
if ($temp < -50 || $temp > 150 || $hum < 0 || $hum > 100) {
http_response_code(400);
die(json_encode(["error" => "Invalid values"]));
}
// Database Connection
try {
$conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
throw new Exception("Connection failed: " . $conn->connect_error);
}
$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("Execution failed: " . $stmt->error);
}
echo json_encode(["status" => "success", "id" => $stmt->insert_id]);
} catch (Exception $e) {
error_log($e->getMessage());
http_response_code(500);
echo json_encode(["error" => "Database error"]);
} finally {
$stmt->close();
$conn->close();
}