Possible Duplicate:
keeping url parameters during pagination
I want to add a parameter to the current url with php, but how do I know if the url already contains a parameter?
Example:
foobar.com/foo/bar/index.php => foobar.com/foo/bar/index.php?myparameter=5 foobar.com/index.php?foo=7 => foobar.com/index.php?foo=7&myparameter=5
The main problem is that I don't know if I need to add a "?".
My code (found it somewhere, but it doesn't work):
<?php if(/?/.test(self.location.href)){ //if url contains ?
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&myparameter=5";
} else {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]?myparameter=5";
}?>
The URL parameters are received from a global variable called
$_GET
which is in fact an array. So, to know if a URL contains a parameter, you can useisset()
function.Afterwards, you can create separate array of such parameter you need to attach to a URL. Like:
Now, to know whether or not, you need a
?
symbol, just count this arrayUpdate:
To know if any parameter is set, just count the
$_GET
you can search for the '?' char like this:
Really you should be using the parse_url() function:
Also you should enclose your array based variables in curly brackets or break out of the string:
$url = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}?myparameter=5";
or
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."?myparameter=5";
enable
error_reporting(E_ALL);
and you will see the error. Notice: Use of undefined constant REQUEST_URI - assumed 'REQUEST_URI' ect