PDA

View Full Version : What php function takes the existing url and append a variable to it



leocrawf
February 12, 2008, 05:40 PM
I want to know how to take the existing url from the address bar and append a variable to it. For example i dont want to mess up the page that is depending on some url vars. So i simple append other variables to the url string. Any ideas

leocrawf
February 15, 2008, 10:33 AM
I found a solution on my php manual.


If you're working with $_GET a lot and need to preserve already set variables in a _link_ for the next page, this function is pretty handy for simplifying the process of generating a new URL:
string setUrlVariables([string var, string value], [varN, valueN], ...)
<?php
function setUrlVariables() {
$arg = array();
$string = "?";
$vars = $_GET;
for ($i = 0; $i < func_num_args(); $i++)
$arg[func_get_arg($i)] = func_get_arg(++$i);
foreach (array_keys($arg) as $key)
$vars[$key] = $arg[$key];
foreach (array_keys($vars) as $key)
if ($vars[$key] != "") $string.= $key . "=" . $vars[$key] . "&";
if (SID != "" && SID != "SID" && $_GET["PHPSESSID"] == "")
$string.= htmlspecialchars(SID) . "&";
return htmlspecialchars(substr($string, 0, -1));
}
?>
You use it like this:
<a href="nextpage.php<?php echo setUrlVariables(); ?>">_link_</a>
In this case setUrlVariables() will simply add all the $_GET variables of the current page/URL and even takes care of the PHPSESSID if you use one (and didn't change the default variable name). The above HREF would complete to e.g.:
"nextpage.php?var=21&PHPSESSID=BI89J"
If you supply arguments, do it like this:
<?php echo setUrlVariables("user", "foobar"); ?>
This would complete the HREF to e.g.:
"nextpage.php?user=foobar&var=21&PHPSESSID=BI89J"
Unsetting variables works by supplying an empty value:
<?php echo setUrlVariables("var", ""); ?>
"nextpage.php?user=foobar&PHPSESSID=BI89J"
setUrlVariables() also makes sure it produces "pretty URLs", so it doesn't output any unnecessary garbage.
<?php
session_destroy();
echo setUrlVariables("user", "");
?>
"nextpage.php"


if you are using it on in a dyanamic table with a recordset you have to save it in file and call it using require_once or you will get an error about "cannot redeclare function".

It works perfectly. No i dont have to spend so much time churning out if else statement to check which variables are declared in url element.

owen
February 15, 2008, 07:05 PM
I'm not even going to ask why you doing this but did you think of using javascript to get the window.location and then adding a string to it?