Building URL (HTTP GET) Query Dynamically

Probably one of the most tedious parts of web development is hand coding a URL with several parameters attached to it. Most beginning developers are use to hand coding URL’s when developing dynamic web apps, much like this.


<a href="page.php?id=<? echo $_GET['id']; ?>&title=<? echo $_GET['title']; ?>&q=<? echo $_GET['q']; ?>">XXX</a>

This isn’t a horrible practice and of course it works, but the code snippet below will make your life ten times easier, believe me. It’s much more expandable and easier to strip and encode data if needed. Plus, the first way can be lead to bugs in your code if not properly handled.

In addition, you need PHP 5+ to use the http_build_query() function. (You could easily build a similar function yourself if needed).


<?
$queries = array();
if(isset($_GET)) {
	$keys = array_keys($_GET);
	foreach($keys as $key) {
		$queries[$key]=$_GET[$key];
	}
}
//http://us2.php.net/http_build_query
$params = http_build_query($queries);
?>

<a href="page.php?<? echo $params; ?>">XXX</a>

If you need to add parameters to your URL, just append to the $queries array.

One Response to “Building URL (HTTP GET) Query Dynamically”

  • Steed

    if it’s $_GET variables your using, the values are already in the url, so you could just use

    $_SERVER['QUERY_STRING']

Trackbacks

  •