From 47400213a0ed41be5f87e6083b111c94f01771b5 Mon Sep 17 00:00:00 2001 From: Eliel de Paula Date: Fri, 2 Mar 2018 03:09:35 -0300 Subject: [PATCH] Avoiding CI Output library This change fix the "Access-Control-Allow-Origin" error running the API between different servers, angular, Ionic etc. --- application/helpers/Json_output_helper.php | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/application/helpers/Json_output_helper.php b/application/helpers/Json_output_helper.php index a9f3633..713ae8d 100644 --- a/application/helpers/Json_output_helper.php +++ b/application/helpers/Json_output_helper.php @@ -4,9 +4,22 @@ function json_output($statusHeader,$response) { - $ci =& get_instance(); - $ci->output->set_content_type('application/json'); - $ci->output->set_status_header($statusHeader); - $ci->output->set_output(json_encode($response)); + if (isset($_SERVER['HTTP_ORIGIN'])) { + header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); + header('Access-Control-Allow-Credentials: true'); + header('Access-Control-Max-Age: 86400'); + } + if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { + + if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) + header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); + + if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) + header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); + + exit(0); + } + http_response_code($statusHeader); + echo json_encode($response); }