开发者

Getting vars from URL

url:

url.com/index.php?id=1000

How to get 1000 fr开发者_运维技巧om id and add it into <h1></h1> on page?


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

echo '<h1>', htmlspecialchars($_GET['id']), '</h1>';


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.


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>


<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.


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜