tags:

views:

37

answers:

3

Using PHP I need to check wether an URL I am appending information to already has a parameter or not.

So if the URL is

http://test.com/url?a=1

I would need to add on &b=2, ie

http://test.com/url?a=1&b=2

However if the URL was

http://test.com/url

I would need to append

http://test.com/url?b=2

Is it possible to check for this within PHP? In summary I need to attach the b=2 parameter using the correct separator character ("?" if there was none in the existing link or "&" if there is already a "?" in the existing link).

Thanks!

Greg

+4  A: 

Do not check but assemble a new one
use $_GET array and http_build_query() function

Col. Shrapnel
ok thanks, interesting idea! I've not used _GET array before, how would I use it bearing in mind I don't know how many parts it may split the URL into?
kitenski
@kitenski you don't have to care. It will be done automatically.
Col. Shrapnel
ok thanks, and please excuse my ignorance, but could you give me an example of how _GET array would work please??
kitenski
@kitenski is it for the current being processed or for the some URL stored in a variable? if latter - use Dennis' answer
Col. Shrapnel
It's already stored in a database, so I can read it into a variable, hence will use Dennis' anaswer, thanks alot for the prompt follow up
kitenski
+1  A: 

You could use parse_url(). Then use parse_str() to get the query pieces, modify the array and use http_build_query() to recreate the query string.

Dennis Haarbrink
A: 

With this function, you can call set('b', 2) or set multiple values at once with set(array('a' => 1, 'b' => 2, 'c' => 3)).

function set($name, $value='', $vars='') {
    if (!$vars) $vars = $_SERVER['QUERY_STRING'];
    parse_str($vars, $a);
    if (!is_array($name)) $name = array($name => $value);
    foreach ($name as $k => $v) {
        $a[$k] = $v;
        if ($v === '') unset($a[$k]);
    }
    $q = '';
    foreach ($a as $k => $v) $q .= ($q ? '&' : '') . $k . '=' . $v;
    return $q ? '?' . $q : '';
}
TRiG