Nick
Nick

Reputation: 906

How is parse_str supposed to be used?

parse_str is not bahaving as I would expect...

I am storing a string to a cookie. It has been prepared using http_build_query and then base64 encoded.

when I read the cookie, I base64_decode, and url_decode. this gives me the following string: (values have been changed in some cases, ip etc.)

$string:

session_id=41a69e102653568b6e483b3eba861484&page_type=&ip=101.101.101.101&host=host101.101.101.101.in-addr.btopenworld.com&user_agent=Mozilla/5.0 (Windows NT 6.1; rv:8.0.1) Gecko/20100101 Firefox/8.0.1&referer=https://domain.com/&referer_domain_tld=domain.com&referer_keywords=&URI=/index.php?path=statistics&fn=test.php&URLdomain.com/index.php?path=statistics&fn=test.php&html_title=&browser=&browser_version=&OS=&OS_version=Windows Windows 7&screen_resolution=&start_date=1323358398&date=1323358398&referer_search_position=&load_time=0.00300002098083&id=&cs=e14272b7e8d9053a5e85ee72083faa5d

here is the code:

    $cookie_data = urldecode(base64_decode($_COOKIE[$stats_cookie_name]));                                  // decode and clean the cookie data. This is the cookie data all decoded and ready to convert to an key->value array.

    $cookie_data_ar = array();

    $cookie_data_ar = parse_str($cookie_data);  

In theory, using parse_str($string) should convert this string into a neat array. But its not. Totally crosseyed now and have wasted hours already. Im sure its somthing stupid, just cant see it. Fresh eyes please!

Upvotes: 0

Views: 795

Answers (3)

Gajus
Gajus

Reputation: 73888

You should check the doc. parse_str returns void. The second argument, however, is assigned (by reference) an array you are after:

void parse_str ( string $str [, array &$arr ] )

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

parse_str has two "modes":

  1. By default, it doesn't return anything (how are you not getting an error or warning here?!) but instead "sets variables in the current scope".

  2. If you provide the second (optional) parameter (which is a reference), "variables are stored in this variable as array elements instead". You want this.

So:

parse_str($cookie_data, $cookie_data_ar);  

This may not be intuitive, but it's certainly clear enough from the documentation.

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45058

parse_str does not return an array (it has a type of void) - you would pass your array as the second parameter, which would in turn be populated accordingly, as in,

parse_str($str, $output);

Upvotes: 0

Related Questions