Pico
Site Admin
Joined: 18 Jan 2004 |
Posts: 248 |
Location: HostMachine.net |
|
 |
When you program in PHP and use GET variables in URL to pass some non-secure variables, for example:
http://domain.com/?show=all&month=12&year=2008
you might have some exercise arround to properly pass all those parameters and to avoid duplicating them, and also to set proper sign ? or & inbetween.
So it might be handy to have a function, which does hard work for you. This PHP function does:
- replace all old GET parameters with new ones
- remove some parameter, if you do not want it anymore
- take care not to duplicate parameters
- or even remove all parameters, except newly defined
Here it is:
############################################################
### Returns new location and replaces GET parameters ------#
###
### If parameter
###
### IMPLICIT = 1 (default)
### function will KEEP all existing parameters in URL query string,
### then ADD all new parameters and REMOVE all those with -1 value
###
### IMPLICIT = 0
### it will REMOVE all GET parameters from URL query string,
### and add (or retain) only those, which are explicitelly defined.
###
### EXAMPLES:
### links(array("foo"=>-1, "bar"=>"blah"),1); // REMOVES "foo" parameter and sets "bar" parameter and KEEPS all other parameters intact
### links(array("foo"=>-1, "bar"=>"blah")) // Same as above (if there is no IMPLICIT definition at the end, it is "1" by default)
### links(array("foo"=>-1, "bar"=>"blah"),0) // REMOVES "foo" parameter and REMOVES also all other parameters, then sets only "bar"
### links(array("bar"=>"blah"),0) // Same as above, because if IMPLICIT is set to "0", you do not need to remove some specific parameter - they are all removed, except those, which are explicitelly defined here
############################################################
function newLink ($pairs=array(),$implicit=1) {
$loc = (strtolower($_SERVER["HTTPS"])=="on") ? "https://" : "http://";
$loc .= $_SERVER["SERVER_NAME"];
$loc .= ($_SERVER["SCRIPT_NAME"]!="/index.php") ? $_SERVER["SCRIPT_NAME"] : "/";
if($implicit==1) $params = array_merge($_GET, $pairs);
else $params = $pairs;
$out = "?";
foreach($params AS $key => $value) {
if($implicit==0) {
if($value==-1 || $value=="") $out .= "";
else $out .= $key."=".$value."&";
}
if($implicit==1) {
if($value==-1) $out .= "";
else $out .= $key."=".$value."&";
}
}
return $loc.rtrim($out,"&?");
} |
In your code, you create new Hyperlinks with GET parameters like this:
inside PHP: echo "<a href=\"" . newLink(array("show"=>"design","month"=>"3")) . "\">Show next month</a>"; |
or inside HTML: <a href="<?=newLink(array("show"=>"design","month"=>"3"));?>">Show next month</a> |
|
_________________ Site admin alias Labsy
Vsi nasveti in tehnične rešitve so podani v dobri veri in za ljudi z razčiščenimi pojmi o veljavni zakonodaji.
Odgovornost prevzemam izključno in samo za tiste posege, ki jih opravim lastnoročno.
|