可能重复:
在分页期间保留url参数
我想用php向当前url添加一个参数,但是如何知道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";
}?>
Run Code Online (Sandbox Code Playgroud)
Sta*_*arx 29
URL参数是从称为$_GET
实际上是数组的全局变量接收的.因此,要知道URL是否包含参数,您可以使用isset()
函数.
if (isset($_GET['yourparametername'])) {
//The parameter you need is present
}
Run Code Online (Sandbox Code Playgroud)
之后,您可以创建需要附加到URL的此类参数的单独数组.喜欢:
if(isset($_GET['param1'])) {
\\The parameter you need is present
$attachList['param1'] = $_GET['param1'];
}
if(isset($_GET['param2'])) {
$attachList['param2'] = $_GET['param2];
}
Run Code Online (Sandbox Code Playgroud)
现在,要知道是否需要?
符号,只需计算这个数组
if(count($attachList)) {
$link .= "?";
// and so on
}
Run Code Online (Sandbox Code Playgroud)
更新:
要知道是否设置了任何参数,只需计算 $_GET
if(count($_GET)) {
//some parameters are set
}
Run Code Online (Sandbox Code Playgroud)
Law*_*one 17
你真的应该使用parse_url()函数:
<?php
$url = parse_url($_SERVER['REQUEST_URI']);
if(isset($url['query'])){
//Has query params
}else{
//Has no query params
}
?>
Run Code Online (Sandbox Code Playgroud)
您还应该将基于数组的变量括在大括号中或者突破字符串:
$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'等
你可以搜索'?' 像这样的char:
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";
}
Run Code Online (Sandbox Code Playgroud)