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



Question:

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.


Solution:1

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


Solution:2

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.


Solution:3

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  


Solution:4

Try this one:

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


Solution:5

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.


Solution:6

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »