Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding query strings in PHP

Okay, so I've written a REST API implementation using mod_rewrite and PHP. I'm accepting a query string via the body of HTTP DELETE requests (... collective groan?). Arguments about the wisdom of both previous statements aside, what I've found is that PHP doesn't automatically parse the request body of DELETE requests (i.e. $_POST is empty despite form-encoded query string appearing in body of request). This didn't particularly surprise me. What I did find surprising was that I've been unable to find a built-in PHP function for parsing a query string?? Have I simply overlooked something? I can do something like:

public function parseQS($queryString, &$postArray){
  $queryArray = explode('&', $queryString);
  for($i = 0; $i < count($queryArray); $i++) {
    $thisElement = split('=', $queryArray[$i]);
    $postArray[$thisElement[0]] = htmlspecialchars(urldecode($thisElement[1]));
  }
}

... it just seems odd that there wouldn't be a PHP built-in to handle this. Also, I suspect I shouldn't be using htmlspecialcharacters & urldecode to scrub form-encoded values... it's a different kind of encoding, but I'm also having trouble discerning which PHP function I should be using to decode form-encoded data.

Any suggestions will be appreciated.

like image 228
codemonkey Avatar asked Nov 30 '22 20:11

codemonkey


2 Answers

There's parse_str. Bad name, but does what you want. And notice that it returns nothing, the second argument is passed by reference.

like image 136
Ionuț G. Stan Avatar answered Dec 04 '22 23:12

Ionuț G. Stan


There is a function that does it - http://php.net/parse_str. Since PHP has to do this for itself, there's no reason not to also open it up for use in the API.

Parses the string into variables void parse_str ( string $str [, array &$arr])

Parses str as if it were the query string passed via a URL and sets variables in the current scope.

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
like image 39
Alister Bulman Avatar answered Dec 05 '22 00:12

Alister Bulman