note 126885 added to function.get-headers
| From: | "https://twitter dot com/jonathansampson" at main dot php dot net | Date: | Sun, 27 Feb 2022 06:32:24 +0000 |
| Subject: | note 126885 added to function.get-headers | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-217665@lists.php.net to get a copy of this message | ||
When requesting headers as an associative array, it's important to note that headers with
different casing will NOT be treated as equal. If your first redirect contains a
"location" header, and your second contains a "Location" header (note the
uppercase L), these will appear as two different keys in your associative array.
The following is one attempt at creating an alternative to get_headers which normalizes the header
names, while also offering the same functionality (with the same signature) as the native
get_headers function:
<?php
function getHeaders ( string $location, bool $associative = true, $context = null ) : array |
bool {
$indexer = 0;
$results = [];
$headers = get_headers( $location, false, $context );
if ( $headers ) {
foreach ( $headers as $header ) {
if ( strpos( $header, ":" ) ) {
$parts = explode( ":", $header, 2 );
$key = strtolower( $parts[0] );
$value = trim( $parts[1] );
if ( !$associative ) {
$results[ $indexer++ ] = "{$key}: {$value}";
continue;
}
/**
* If the header name hasn't yet been encountered, we
* add it to the
results array, storing the value as
* a string.
*
* If the header name has been encountered already (it
* has already been stored in the results array), and
* is an array, we'll push the current value.
*
* If the header name has been encountered, but currently
* points to a string, we will replace with an array, but
* keep the original string at index 0.
*/
if ( !key_exists( $key, $results ) ) {
$results[ $key ] = $value;
} else if ( is_array( $results[ $key ] ) ) {
array_push( $results[ $key ], $value );
} else {
$results[ $key ] = [ $results[ $key ], $value ];
}
continue;
}
// No ':' found in the header, so we'll preserve as-is.
$results[ $indexer++ ] = $header;
}
return $results;
}
return false;
}
?>
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.135 (proxied: 2600:1700:2ab0:37b8:6cff:82c9:eb9a:41ef)
----
Manual Page -- https://php.net/manual/en/function.get-headers.php
Edit -- https://main.php.net/note/edit/126885
Del: integrated -- https://main.php.net/note/delete/126885/integrated
Del: useless -- https://main.php.net/note/delete/126885/useless
Del: bad code -- https://main.php.net/note/delete/126885/bad+code
Del: spam -- https://main.php.net/note/delete/126885/spam
Del: non-english -- https://main.php.net/note/delete/126885/non-english
Del: in docs -- https://main.php.net/note/delete/126885/in+docs
Del: other reasons-- https://main.php.net/note/delete/126885
Reject -- https://main.php.net/note/reject/126885
Search -- https://main.php.net/manage/user-notes.php