views:

62

answers:

6

Ok, so I have let's say this page http://mypage.com/index.php?id=something. I want to have in this page the link which would go to the http://mypage.com/index.php?id=something&sub=1. And to do that I have to add a href to my index.php file like this
echo '<a href="index.php?id=something&sub=1">go here</a>';. Is it possible to do this thing shorter? I mean just adding sub=1 somehow? Thanks.

+1  A: 

In PHP you can do something like:

echo '<a href="' . $_SERVER['REQUEST_URI'] . '&sub=1">go here</a>'

In JavaScript, you could do:

location.search += "&sub=1";

But this is not really a good reason to require JavaScript.

Matthew Flaschen
Scott Stafford
That's true. In the OP's code, there is a query string.
Matthew Flaschen
A: 

Try this one:

$_SERVER[PHP_SELF] + "&sub=1";

sTodorov
`PHP_SELF` is not a constant, but a string and should thus be encapsulated in quotes. Additionally, it does not contain the query string.
nikc
Thanks for the clarification, man. Very nice
sTodorov
+1  A: 

In php you can get:

$_SERVER['REQUEST_URI'];

That should give you the requested url, but adding &sub=1 is risky in case the page got called without a query string because it would result in:

index.php&sub=1
jeroen
A: 

Using PHP, you can use $_SERVER['REQUEST_URI'] to get the pages' URL. You can then modify that as you would any other string.

See Predefined variables in the PHP manual.

nikc
A: 

You could do the following:

echo '<a href="' . $_SERVER['REQUEST_URI'] . ($_SERVER['QUERY_STRING'] == '' ? '?' : '&') . 'sub=1">go here</a>';

But sooner or later you will have to face the problem that you may "add" a parameter that is already in the query string. So I would recommend to write a function/method that handles adding/removing query parameters to a URL.

StefanMacke
A: 

There is PHP command called http_build_url that is specifically for your type of use case.

This is how you would use it for your example:

http_build_url($url_string,
    array(
        "query" => "sub=1"
    ),
    HTTP_URL_JOIN_QUERY
);
GoalBased