Getting vars from URL

2019-02-15 13:38发布

url:

url.com/index.php?id=1000

How to get 1000 from id and add it into <h1></h1> on page?

标签: php url
6条回答
手持菜刀,她持情操
2楼-- · 2019-02-15 14:14

Use $_GET:

$id = isset($_GET['id']) ? (int) $_GET['id'] : FALSE;
echo '<h1>', $id, '</h1>';

If the URL is within a variable, use parse_urlDocs and parse_strDocs:

$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:

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. This also helps to better structure your code for re-usability.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-02-15 14:14
$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.

查看更多
何必那么认真
4楼-- · 2019-02-15 14:18

You can either use the global array $_REQUEST[], or in your case the explicit $_GET:

<h1><?php echo $_GET['id']; ?></h1>

To prevent XSS you should also use htmlspecialchars:

<h1><?php echo htmlspecialchars($_GET['id']); ?></h1>
查看更多
混吃等死
5楼-- · 2019-02-15 14:23

You fetch the number from the $_GET array and escape it with htmlspecialchars to prevent XSS attacks:

echo '<h1>', htmlspecialchars($_GET['id']), '</h1>';
查看更多
手持菜刀,她持情操
6楼-- · 2019-02-15 14:25
<h1><?php echo $_REQUEST["id"]; ?></h1>
查看更多
贼婆χ
7楼-- · 2019-02-15 14:35

You should use the $_GET superglobal array, which holds querystring parameters.

For example: <h1><?php echo $_GET['id']; ?></h1>

查看更多
登录 后发表回答