Robin
Robin

Reputation: 3840

Pass current GET Variables with href

Let's say I am on www.example.com/?par1=test and I have a Link like: <a href="/subpage">Link text</a>.

How to pass the GET Variable to the subpage, without reading every Parameter e.G. $_GET["par1"] and pass it to the Link by hand.

Upvotes: 1

Views: 1958

Answers (7)

Nimrod007
Nimrod007

Reputation: 9913

this is a example of how to do this :

<?php
echo print_r($_GET);
echo "<br>";
echo "www.mysite.com/index.php?".http_build_query($_GET);
?>

will print : (if url is : http://www.mysite.com/index.php?this=1&that=2 )

Array ( [this] => 1 [that] => 2 ) 1

www.mysite.com/index.php?this=1&that=2

Upvotes: 0

BenLanc
BenLanc

Reputation: 2434

As with many problems, there are many solutions!

The simplest is probably just to append your URL with the contents of $_SERVER['QUERY_STRING'], e.g.:

<a href="/somefile?<?php echo $_SERVER['QUERY_STRING'] ?>">somefile</a>

But this does rely on your webserver correctly passing through the correct parameters I believe. Apache should do this out of the box with mod_php, but FastCGI based PHP may need some additional config.

Take a look at the documentation for the $_SERVER variable

Upvotes: 0

Amir Habibzadeh
Amir Habibzadeh

Reputation: 437

$_SERVER['QUERY_STRING'] contains the data that you are looking for.

PHP: $_SERVER - Manual

Upvotes: 4

mr. Pavlikov
mr. Pavlikov

Reputation: 1012

If you want to pass all get variables to next page just do next thing:

$href = '/somepage/';
if ($_GET) {
    $href .= strpos($href, '?') === false ? '?' : '&';
    $href .= http_build_query($_GET);
}

Then echo this href

<a href="<?=$href;?>">my link</a>

Upvotes: 4

AlexP
AlexP

Reputation: 9857

You could create a function to aid your link generation.

Obviously this is a simple example but you could easily extend it.

    function getLink($url, array $params = array())
    {
        if (empty($params)) return $url;

        $url .= '?';
        foreach($params as $param => $value) {
            $url .= $param .'='. $value;
        }
        return $url;
    }

    $params = array(
        'test' => 1,
        'foo' => 'hello',
        'bar' => 'test',
    );
    echo getLink('my/target/page.php', $params);

The $params array could be substituted for the super-global $_GET to make life easier!

Upvotes: 0

user2188149
user2188149

Reputation:

<a href='www.example.com.br?pas1=<?php echo $variavel  ?>'>Link</a>;

Upvotes: 0

Expedito
Expedito

Reputation: 7795

Use parse_url. It returns an array like:

$out = parse_url('www.example.com/?par1=test');
var_dump($out);

Output:

Array
(
[path] => www.example.com/
[query] => par1=test
)

Upvotes: 1

Related Questions