[英]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
. 好的,所以我说这个页面
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
. 我想在此页面中找到指向
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 为此,我必须像这样在我的index.php文件中添加
a href
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? 我的意思是只是以某种方式添加
sub=1
? Thanks. 谢谢。
In PHP you can do something like: 在PHP中,您可以执行以下操作:
echo '<a href="' . $_SERVER['REQUEST_URI'] . '&sub=1">go here</a>'
In JavaScript, you could do: 在JavaScript中,您可以执行以下操作:
location.search += "&sub=1";
But this is not really a good reason to require JavaScript. 但这并不是需要JavaScript的充分理由。
In php you can get: 在php中,您可以获得:
$_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: 这应该为您提供所需的URL,但是如果在没有查询字符串的情况下调用该页面,则添加
&sub=1
是有风险的,因为这将导致:
index.php&sub=1
Try this one: 试试这个:
$_SERVER[PHP_SELF] + "&sub=1"; $ _SERVER [PHP_SELF] +“&sub = 1”;
Using PHP, you can use $_SERVER['REQUEST_URI']
to get the pages' URL. 使用PHP,可以使用
$_SERVER['REQUEST_URI']
获取页面的URL。 You can then modify that as you would any other string. 然后,您可以像修改其他任何字符串一样修改它。
See Predefined variables in the PHP manual. 请参见PHP手册中的预定义变量 。
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.
因此,我建议编写一种函数/方法来处理向URL添加/删除查询参数的操作。
There is PHP command called http_build_url
that is specifically for your type of use case. 有一个名为
http_build_url
PHP命令,专门用于您的用例类型。
This is how you would use it for your example: 这是您将其用于示例的方式:
http_build_url($url_string,
array(
"query" => "sub=1"
),
HTTP_URL_JOIN_QUERY
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.