所以,我有一些看起来有点像这样的PHP代码:
<body>
The ID is
<?php
echo $_GET["id"] . "!";
?>
</body>
Run Code Online (Sandbox Code Playgroud)
现在,当我传递一个ID,http://localhost/myphp.php?id=26
它可以正常工作,但如果没有像那样的ID http://localhost/myphp.php
它输出:
The ID is
Notice: Undefined index: id in C:\xampp\htdocs\myphp.php on line 9
!
Run Code Online (Sandbox Code Playgroud)
我已经搜索了一种方法来解决这个问题,但我找不到任何方法来检查是否存在URL变量.我知道必须有办法.
可能重复:
在分页期间保留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)