Search code examples
phphttp-headersarray-difference

script to compare HTTP headers


I am looking for a way to write a function in a script to show what differences there are between array values

Edit: added PHP code (and simplified...)

Array
(
    [0] => HTTP/1.1 200 OK
    [Content-Type] => text/html; charset=UTF-8
    [Connection] => close
    [X-Powered-By] => PHP/5.6.30
    [X-Content-Type-Options] => nosniff
    [Server] => nginx

)
Array
(
    [0] => HTTP/1.1 200 OK
    [Server] => Apache/2.4.27 (Amazon) OpenSSL/1.0.1k-fips PHP/5.6.30
    [X-Powered-By] => PHP/5.6.30
    [Content-Length] => 11
    [Connection] => close
    [Content-Type] => text/html; charset=UTF-8
)

Solution

  • To get the headers in PHP use get_headers.

    You can iterate over your first array, and use the key to compare it against the second array. This will show difference between first and second; to see differences in the second unset the values of the second in the first, then iterate over the second and everything present there wasnt present in the first.

    foreach($ar1 as $key => $value) {
        if(empty($ar2[$key])) {
            $missing_keys[] = $key; 
        } elseif ($ar2[$key] != $value) {
            $non_matching_values[$key] = $value . '|<-deviation->|' . $ar2[$key];
        }
        unset($ar2[$key]);
    }
    foreach($ar2 as $key => $value) {
        $missing_keys[] = $key;
    }
    print_r($missing_keys);
    print_r($non_matching_values);
    

    Demo: https://3v4l.org/JV40E