Skip to content
Advertisement

PHP http code 0 unable to read custom headers

I have a php script which is being called in an angular project. I always get the response code as 0. I can find the request headers in chrome debugging section, but when i see in script it a always empty. Also the php script is called twice with request method ‘options’ and ‘get’. Iam not able to proceed further to get the details. Iam working on a windows , PHP7,iis server.

<?php
ob_start();
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'testing'); //testing, production
ini_set('display_errors', '1');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
    header('Access-Control-Allow-Headers: api-method,api-url,authorization,token, Content-Type');
    header('Content-Length: 0');
    header('Content-Type: text/plain');
    die();
}else{
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");
    header("Content-Type: application/json");
}


echo "header " .getallheaders()['api-method'] . '<br>';
if ((empty(getallheaders()['api-method']) || empty(getallheaders()['api-url'])) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    echo json_encode(['msg' => 'Invalid request']);
        exit;
}
$params = [];
$api_url = getallheaders()['api-url'];
$api_method = getallheaders()['api-method'];


if ($api_method == 'post') {
    $params = json_decode(file_get_contents('php://input'), TRUE);
    if (empty($params)) {
        $params = $_POST;
    }
    $headers = ["Content-Type: application/x-www-form-urlencoded", "Cache-Control: no-cache"];
} else {
    $headers = [];
}

//read headers
foreach (getallheaders() as $name => $value) {
    $key = strtolower($name);
    if (strtolower($name) == 'mobilenumber') {
        array_push($headers, "$key: $value");
    } else if (strtolower($name) == 'branch') {
        array_push($headers, "$key: $value");
    } else if (strtolower($name) == 'authorization') {
        array_push($headers, "$key: $value");
    }
}

$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $api_url);
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 20); 
curl_setopt($handle, CURLOPT_TIMEOUT, 400);
echo 'Curl error: ' . curl_error($handle);
if ($api_method == 'post') {
    curl_setopt($handle, CURLOPT_POST, true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($params));
}
$response = curl_exec($handle);
$contentType = curl_getinfo($handle, CURLINFO_CONTENT_TYPE);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
print curl_error($handle);

if (ENVIRONMENT == 'testing') {
    $log = 'Request Date:' . date("Y-m-d H:i:s") . '<br>';
    $log .= 'Request url: ' . $api_url . '<br>';
    $log .= 'Request Method: ' . $api_method . '<br>';
    $log .= 'Content Type: ' . $contentType . '<br>';    $log .= 'Http Code: ' . $code . '<br>';
    $log .= '<code>response: ' . $response . '</code>';
    write_log($log);
}

if ($code == 200) {
    http_response_code($code);
    if (checkjson($response)) {
        echo $response;
    } else {
        if (strpos($api_url, 'AddUser') !== false) {
            if ($response == "error") {
                http_response_code(200);
                echo json_encode(['status' => 'success']);
                exit;
            }
        }
        if (strpos($api_url, 'EditUser') !== false) {
            if ($response == "error") {
                http_response_code(200);
                echo json_encode(['status' => 'success']);
                exit;
            }
        }
        if ($response == "error") {
            http_response_code(404);
            echo json_encode(['status' => $response]);
        } else if ($response == "success") {
            http_response_code(200);
            echo json_encode(['status' => $response]);
        } else if ($response == "user already exist") {
            http_response_code(409);
            echo json_encode(['status' => $response]);
        } else {
            echo json_encode(['data' => $response]);
        }
    }
} else {
    http_response_code($code);
    echo json_encode(['msg' => 'empty response'.$code.$handle]);
}
if ($code == 0) {
    print_r(curl_getinfo($handle));
    exit;
}

function write_log($data = '')
{
    file_put_contents("log.html", '<div style="max-width:100%;border:1px solid #ccc; padding:5px">' . $data . '</div><br>', FILE_APPEND | LOCK_EX);
}

function checkjson($str)
{
    return json_decode($str, true);
}


Advertisement

Answer

You can use to call custom headers as an array

$headersArray = array();
foreach ($_SERVER as $key => $value) {
    if (strpos($key, 'HTTP_') === 0) {
        $headersArray[str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
    }
}

Refer : https://stackoverflow.com/a/11709337/11298876, this answer was really helpful. Now you can use headers array to call each header (Note it will be in camel case)

$api_url = $headersArray['ApiUrl'];
$api_method = $headersArray['ApiMethod'];
$mobile = $headersArray['Mobilenumber'];
$brand = $headersArray['Branch'];
$auth = $headersArray['Authorization'];

to get the actual headers.

Then finally you can use an array_push(because you have used it in your script) like this

array_push($headers, "mobilenumber: ".$headersArray['Mobilenumber'], "branch: ".$headersArray['Branch'],"authorization: ".$headersArray['Authorization']);

to send the headers.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement