phparrayscontent-lengthget-headers

Check for key in array php


I am using get_headers() and I want to return the content length. In the array below content length is key number 9, however I find that the content length is not always key number 9. I'm not sure why it is not always the same key? How do I search an array and always return the content length no matter what key it is? As I am using this in a function so the actual filesize of the file will be differen't each time. My example code is below. Thanks in advance.

Array ( [0] => HTTP/1.0 200 OK [1] => Server: Apache [2] => Pragma: public [3] => Last-Modified: Sun, 01 Apr 2012 07:59:46 GMT [4] => ETag: "1333267186000" [5] => Content-Type: text/javascript [6] => Cache-Control: must-revalidate, max-age=0, post-check=0, pre-check=0 [7] => Expires: Sun, 01 Apr 2012 10:27:26 GMT [8] => Date: Sun, 01 Apr 2012 10:27:26 GMT [9] => Content-Length: 31650 [10] => Connection: close [11] => Set-Cookie: JSESSIONID=M0V4NTTVSIB4WCRHAWVSFGYKE2C0UIV0; path=/ [12] => Set-Cookie: DYN_USER_ID=2059637079; path=/ [13] => Set-Cookie: DYN_USER_CONFIRM=6c6a03988da3de6d704ce37a889b1ec8; path=/ [14] => Set-Cookie: BIGipServerdiy_pool=637871882.20480.0000; path=/ )

function headInfo($url) {
    $header = get_headers($url);
    $fileSize = $header[9];
    return array($header, $fileSize);
}

Solution

  • http://php.net/get_headers

    The second parameter:

    If the optional format parameter is set to non-zero, get_headers() parses the response and sets the array's keys.

    So, just pass 1 as the second parameter, and $header['Content-Length'] will be what you've after.