简体   繁体   中英

How to add a little to URL instead of copying and pasting it all?

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.

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.

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

Try this one:

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

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.

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.

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
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM