The Agri-Tech Builder

Coding smart solutions for off-grid farming

Syncing Offline Mobile App Data to a Local PHP Server

Author: Marcial Rey (In Between Bamboos Farm)


Building mobile apps for agriculture comes with a unique challenge: the internet rarely reaches the middle of a farm. As I build my Uni-Farm mobile app using Flutter, I had to adopt an "offline-first" architecture. This means the app saves farm data (like harvest weights or leaf scans) directly to the phone's local storage while out in the fields.

However, that data needs to eventually reach my main database. The solution? I coded a PHP API endpoint on my local server. When I walk back to the farmhouse and my phone reconnects to the local Wi-Fi, the Flutter app silently pushes all the saved data to this PHP script.

The Code: The PHP Sync Receiver

Here is the exact PHP code that acts as the "receiver." It catches the JSON data sent by the mobile app and securely inserts it into the farm's MySQL database.

<?php
// offline-receiver.php (API Endpoint)

// 1. Read the incoming JSON payload from the mobile app
$json_data = file_get_contents('php://input');
$data = json_decode($json_data, true);

if ($data) {
    // 2. Connect to the local farm database
    $conn = new mysqli('localhost', 'root', '', 'agritech_db');
    
    if ($conn->connect_error) {
        die(json_encode(["status" => "error", "message" => "Connection failed."]));
    }

    // 3. Prepare and execute the secure SQL insert
    $device_id = $conn->real_escape_string($data['device_id']);
    $sync_payload = $conn->real_escape_string(json_encode($data['payload']));
    $sync_time = date("Y-m-d H:i:s");
    
    $sql = "INSERT INTO offline_sync_logs (device_id, payload_data, synced_at) 
            VALUES ('$device_id', '$sync_payload', '$sync_time')";
            
    if ($conn->query($sql) === TRUE) {
        // Send a success ping back to the phone so it clears its local storage
        echo json_encode(["status" => "success", "message" => "Data securely synced!"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Database error."]);
    }
    
    $conn->close();
}
?>

By relying on a local server network, the farm's digital infrastructure stays completely functional even when the main internet provider goes down!