Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache rewrite query string (checkbox array)

How is it possible to rewrite the query string like:

test.php?cat1[]=18&cat1[]=687&xxx[]=5&xxx[]=3&xxx[]=1&yyy[]=6

to

test.php?cat1=18,687,5&xxx=3,1&yyy=6

Note that the parameters (name and value pairs) are generated dynamically.

like image 979
jan Avatar asked Dec 16 '22 19:12

jan


1 Answers

Here's a short php script that creates the query string that you want. It's best not to do this part using mod_rewrite, because it's simply outside of that scope:

<?php

$ret = "";
foreach($_GET as $key=>$val) {
  if(is_array($val)) {
    // Create the comma separated string
    $value = $val[0];
    $length = count($val);
    for($i=1; $i < $length; $i++) {
      $value .= ',' . $val[$i];
    }
    $ret .= "$key=$value&";
  } else {
    $ret .= "$key=$val&";
  }
}

// Remove last '&'
$ret = substr($ret , 0, strlen($ret)-1);

// Redirect the browser
header('HTTP/1.1 302 Moved');
header("Location: /test.php?" . $ret);

?>

If you save that script as /rewrite.php, for example, then you can include these rules in the .htaccess file to reroute requests with query strings containing arrays to /rewrite.php:

RewriteCond %{QUERY_STRING} \[\]
RewriteRule ^test.php /rewrite.php [L,QSA]

Then the rewrite.php script will rewrite the query string and redirect the browser with the concatenated query string.

like image 186
Jon Lin Avatar answered Dec 30 '22 08:12

Jon Lin