Search code examples
phpioshttp-headerslocalhostnsmutableurlrequest

Validate custom HTTP header in PHP which sent by iOS


What I'm trying to do is, sending a HTTP request with custom header from my iOS application to my localhost which runs XAMPP in my MAC machine. Then there is a PHP page which check my particular header and respond according to that.

Following is the iOS part

NSString *urlStr = @"http://127.0.0.1/restapi/index.php?name=anuja";

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

[request setURL:[NSURL URLWithString:urlStr]];

[request setHTTPMethod:@"GET"];

[request addValue:@"apiuser" forHTTPHeaderField:@"X-USERNAME"];

NSLog(@"%s - %d # allHTTPHeaderFields = %@", __PRETTY_FUNCTION__, __LINE__, [request allHTTPHeaderFields]);

NSURLResponse *response;
NSError *error;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString *responseStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"%s - %d # responseStr = %@", __PRETTY_FUNCTION__, __LINE__, responseStr);

And following is the way I'm checking that particular header from my PHP script

        if (isset($_GET["name"])) {

            foreach (headers_list() as $name => $value) {

                if (strcmp($value, "X-USERNAME: apiuser") == 0) {

                    $name = $_GET["name"];

                    $result = json_encode(array('name' => $name), JSON_FORCE_OBJECT);

                    sendResponse(200, json_encode($result));

                    return true;
                }
            }

            sendResponse(203, 'Non-Authoritative Information');
            return false;
        }

I'm always getting "Non-Authoritative Information" as response. But I need to get the response with my name which is in 200 status code.

As far as I can understand the problem is with the way I checked the HTTP header inside my PHP script

if (strcmp($value, "X-USERNAME: apiuser") == 0)

May be that is not the standard way to check header values and compare it with a pre defined string value in PHP. Is there any way to print the HTTP request header which it receives from PHP side?


Solution

  • headers_list() returns an array of response headers that were already sent or are ready to be sent.

    To inspect request headers, use getallheaders(). It returns an associative array of header name and value pairs, so to check if X-USERNAME header is present and its value is apiuser, you'd do something like:

    $request_headers = getallheaders();
    if(isset($request_headers['X-USERNAME']) && $request_headers['X-USERNAME'] == 'apiuser') {
        // do stuff
    }