0) { ob_end_clean(); } // Headers CORS pour permettre les requêtes cross-origin (applications mobiles) $origin = $_SERVER['HTTP_ORIGIN'] ?? '*'; // Configurer les headers CORS header("Access-Control-Allow-Origin: $origin"); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With, X-App-Identifier, X-Client-Type'); header('Access-Control-Expose-Headers: Content-Length, X-Kuma-Revision'); // Définir les headers de réponse header('Content-Type: application/json; charset=utf-8'); header('X-Content-Type-Options: nosniff'); // Définir le code de statut http_response_code($status); // Ajouter status et message à la réponse si non présents if (!isset($data['status'])) { if ($status >= 200 && $status < 300) { $data['status'] = 'success'; } else { $data['status'] = 'error'; } } if (!isset($data['message']) && isset($data['error'])) { $data['message'] = $data['error']; } // Sanitize data to ensure valid UTF-8 before encoding $sanitizedData = self::sanitizeForJson($data); // Encoder et envoyer la réponse $jsonResponse = json_encode($sanitizedData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); // Vérifier si l'encodage a échoué if ($jsonResponse === false) { error_log('Erreur d\'encodage JSON: ' . json_last_error_msg()); $jsonResponse = json_encode([ 'status' => 'error', 'message' => 'Erreur d\'encodage de la réponse', 'debug_info' => json_last_error_msg() ]); } // Log de débogage error_log('Envoi de la réponse JSON: ' . $jsonResponse); // Envoyer la réponse echo $jsonResponse; // S'assurer que tout est envoyé flush(); } /** * Sanitize data recursively to ensure valid UTF-8 encoding for JSON * * @param mixed $data The data to sanitize * @return mixed The sanitized data */ private static function sanitizeForJson($data) { if (is_string($data)) { // Replace invalid UTF-8 characters if (!mb_check_encoding($data, 'UTF-8')) { // Try to convert from other encodings $encodings = ['ISO-8859-1', 'Windows-1252']; foreach ($encodings as $encoding) { $converted = mb_convert_encoding($data, 'UTF-8', $encoding); if (mb_check_encoding($converted, 'UTF-8')) { return $converted; } } // If conversion fails, strip invalid characters return mb_convert_encoding($data, 'UTF-8', 'UTF-8'); } return $data; } else if (is_array($data)) { // Recursively sanitize array elements foreach ($data as $key => $value) { $data[$key] = self::sanitizeForJson($value); } } return $data; } }