从 URL 获取变量 [英] Getting vars from URL
问题描述
网址:
url.com/index.php?id=1000
如何从id
获取1000
并将其添加到页面中?
How to get 1000
from id
and add it into <h1></h1>
on page?
推荐答案
使用$_GET
:
$id = isset($_GET['id']) ? (int) $_GET['id'] : FALSE;
echo '<h1>', $id, '</h1>';
如果 URL 在变量内,使用 parse_url
Docs 和 parse_str
文档:
If the URL is within a variable, use parse_url
Docs and parse_str
Docs:
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $vars);
$id = isset($vars['id']) ? (int) $vars['id'] : FALSE;
echo '<h1>', $id, '</h1>';
如果您已启用注册全局变量(这是非常不鼓励,所以只是为了完整性),你可以这样做:
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>';
通常在应用程序中,您希望与 $_GET
分离并将其包装到请求对象中:
Normally in an application you want to de-couple from $_GET
and wrap it into a request object:
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>';
完成后,您可以稍后将请求实现替换为另一个,以使用非 http 请求运行和测试您的应用程序.这也有助于更好地构建代码以实现可重用性.
That done, you can replace later on the request implementation with another to run and test your application with non-http requests. This also helps to better structure your code for re-usability.
这篇关于从 URL 获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!