Getting vars from URL

2019-02-15 13:54发布

问题:

url:

url.com/index.php?id=1000

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

回答1:

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.



回答2:

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

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


回答3:

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>


回答4:

<h1><?php echo $_REQUEST["id"]; ?></h1>


回答5:

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



回答6:

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

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



标签: php url