Proxying Cookies with Drupal
It's the minor things that get you into trouble sometimes. For instance, when I used drupal_http_request to do some proxying of content I ran into a little quirk of Drupal. If you get cookie headers back Drupal will go ahead and combine them all into a comma-separated list. If you look at the code you can plainly see where it does this and the rationale in the Request For Comments (RFC) 2109. The unfortunate part is that RFC 2109 has been made obsolete by RFC 6265 which was published in April 2011. If you blindly take this cookie header and pass it back to the client only the first cookie is actually captured. Whoops.
Normally I'd just explode it and call it a day. Unfortunately the format for the cookie expiration is "Wdy, DD-Mon-YY HH:MM:SS GMT" (as per section 10.1.2). With just a little regex your problem is solved. It means having to do some annoying workarounds, but here is a solution:
function my_module_proxy_url($url) {<br>
$result = drupal_http_request($url);<br><br> if (200 == $result->code) {<br> foreach ($result->headers as $key => $value) {<br> if (strcasecmp($key, 'set-cookie')) {<br> $cookies = preg_split('/(?<=\S),(?:\S)/', $value);<br>
foreach ($cookies as $cookie) {<br>
// Send separately since drupal_add_http_header concatenates with commas<br> header($key . ': ' . $cookie, FALSE);<br> }<br> }<br> else {<br> drupal_add_http_header($key, $value);<br> }<br> }<br>
}<br>}
It's always fun when Drupal behaves according to obsolete RFCs. Learn how to proxy http requests with Drupal and actually get useable cookies.