June 3, 2012

Check if url contains parameters

Question by Puyol

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"; 
}?>

Answer by Starx

The URL parameters and received from a global variable called $_GET which is in fact an array. So, to know if a URL contains a parameter, you can use isset() function.

if (isset($_GET['yourparametername'])) {
    //The parameter you need is present
}

After wards, you can create separate array of such parameter you need to attach to a URL. LIke

if(isset($_GET['param1'])) {
    \The parameter you need is present
    $attachList['param1'] = $_GET['param1'];
}
if(isset($_GET['param2'])) {
    $attachList['param2'] = $_GET['param2];
}

Now, to know whether or not, you need a ? symbol, just count this array

if(count($attachList)) {
    $link .= "?";
    // and so on
}

Update:

To know if any parameter is set, just count the $_GET

if(count($_GET)) {
     //some parameters are set
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!