可能重复:
分页过程中保持URL参数
我想一个参数添加到用PHP当前的URL,但我怎么知道,如果网址已经包含一个参数?
例:
foobar.com/foo/bar/index.php => foobar.com/foo/bar/index.php?myparameter=5 foobar.com/index.php?foo=7 => foobar.com/index.php?foo = 7&myparameter = 5
主要的问题是,我不知道我是否需要添加一个“?”。
我的代码(发现它的地方,但它不工作):
<?php if(/?/.test(self.location.href)){ //if url contains ?
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&myparameter=5";
} else {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]?myparameter=5";
}?>
从全局变量接收的URL的参数调用$_GET
这实际上是一个数组。 所以,要知道如果一个URL包含一个参数,你可以使用isset()
的功能。
if (isset($_GET['yourparametername'])) {
//The parameter you need is present
}
之后,你可以创建你需要连接到一个URL这样的参数的单独的数组。 喜欢:
if(isset($_GET['param1'])) {
\\The parameter you need is present
$attachList['param1'] = $_GET['param1'];
}
if(isset($_GET['param2'])) {
$attachList['param2'] = $_GET['param2];
}
现在,知道与否,你需要一个?
符号,算了算这阵
if(count($attachList)) {
$link .= "?";
// and so on
}
更新:
要知道,如果任何参数设置,只需算$_GET
if(count($_GET)) {
//some parameters are set
}
真的是你应该使用parse_url()函数:
<?php
$url = parse_url($_SERVER['REQUEST_URI']);
if(isset($url['query'])){
//Has query params
}else{
//Has no query params
}
?>
你还应该附上基于阵列的变量,大括号或打出来的字符串:
$url = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}?myparameter=5";
要么
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."?myparameter=5";
使error_reporting(E_ALL);
你会看到错误。 注意:未定义的常量REQUEST_URI的使用 - 假设“REQUEST_URI” ECT
你可以搜索“?” 炭是这样的:
if (strpos($_SERVER[REQUEST_URI], '?')) { // returns false if '?' isn't there
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&myparameter=5";
} else {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]?myparameter=5";
}