[英]Getting vars from URL
url: 网址:
url.com/index.php?id=1000
How to get 1000
from id
and add it into <h1></h1>
on page? 如何从
id
获取1000
并将其添加到页面上的<h1></h1>
?
您从$ _GET数组中获取数字并使用htmlspecialchars转义它以防止XSS攻击:
echo '<h1>', htmlspecialchars($_GET['id']), '</h1>';
You should use the $_GET superglobal array, which holds querystring parameters. 您应该使用$ _GET超全局数组,该数组包含查询字符串参数。
For example: <h1><?php echo $_GET['id']; ?></h1>
例如:
<h1><?php echo $_GET['id']; ?></h1>
<h1><?php echo $_GET['id']; ?></h1>
You can either use the global array $_REQUEST[]
, or in your case the explicit $_GET
: 您可以使用全局数组
$_REQUEST[]
,或者在您的情况下使用显式$_GET
:
<h1><?php echo $_GET['id']; ?></h1>
To prevent XSS you should also use htmlspecialchars: 要防止XSS,您还应该使用htmlspecialchars:
<h1><?php echo htmlspecialchars($_GET['id']); ?></h1>
<h1><?php echo $_REQUEST["id"]; ?></h1>
$id = $_GET["id"];
//Perform checks on $id
echo '<h1>'.$id.'<h1/>';
If you wish to inject it into h1, you can echo it back and use javascript to set the innerhtml of the tag. 如果你想将它注入h1,你可以回复它并使用javascript来设置标签的innerhtml。
Use $_GET
: 使用
$_GET
:
$id = isset($_GET['id']) ? (int) $_GET['id'] : FALSE;
echo '<h1>', $id, '</h1>';
If the URL is within a variable, use parse_url
Docs and parse_str
Docs : 如果URL在变量中,请使用
parse_url
Docs和parse_str
文档 :
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $vars);
$id = isset($vars['id']) ? (int) $vars['id'] : FALSE;
echo '<h1>', $id, '</h1>';
Edit: 编辑:
If you've got register globals enabled (which is highly discouraged, so just for completeness), you can do this: 如果你已经启用了注册全局变量 ( 非常不鼓励,那么只是为了完整性),你可以这样做:
$id = isset($id) ? (int) $id : FALSE;
echo '<h1>', $id, '</h1>';
Normally in an application you want to de-couple from $_GET
and wrap it into a request object: 通常在您想要从
$_GET
解耦并将其包装到请求对象的应用程序中:
class Request
{
public function getParameter($name, $default = NULL)
{
return isset($_GET[$name]) ? $_GET[$name] : $default;
}
public function getParameterInt($name, $default = NULL)
{
$value = $this->getParameter($name, NULL);
return NULL === $value ? $default : (int) $value;
}
}
$request = new Request();
$id = $request->getParameterInt('id');
echo '<h1>', $id, '</h1>';
That done, you can replace later on the request implementation with another to run and test your application with non-http requests. 完成后,您可以稍后在请求实现上替换另一个,以使用非http请求运行和测试您的应用程序。 This also helps to better structure your code for re-usability.
这也有助于更好地构建代码以实现可重用性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.