October 6, 2009

Preserve query strings

As you keep developing your website, you’ll notice that occasionally you’ll need to keep track of more than one query string at a time. Eventually, you’ll find that this gets to be such a task in itself, you’ll wish there was an easier way to do it. That is what the preserve_links() function does. It takes the url, grabs all the query strings, updates the query string based on what you want, and then uploads it all.

<?php 
function preserve_links($option,$value){
	$keys = array_keys($_GET); 
	$str = $_SERVER['PHP_SELF'].'?'.$option.'='.$value; 
 
	foreach($keys as $key=>$val){
		$tmp[$val] = addslashes(strip_tags($_GET[$val])); 
		if($tmp[$val] != '' && $option != $val){
			$str .= '&'.$val.'='.$tmp[$val]; 
		}
	}
 
	return $str; 
}
?>

As you can see it’s fairly straight forward. You pass the query string you want to set as the arguments. It doesn’t matter if the query string is one that is already present in the url as it will be overwritten. For example if your url is:

index.php?page=4&id=12

running the command preserve_links(‘page’,5); will generate the string of index.php?page=5&id=12

If you wish to append a query string preserve_links(‘session’,38581); will generate a url of index.php?session=38581&page=5&id=12

It’s a quick nifty little function that saves you a lot of headaches!

Leave a Reply