PHP Four examples of how to get URL parameters

  • 2021-01-19 22:03:15
  • OfStack

$_GET['name'] $_GET['name'] $_GET['name'] $_GET['name'] So, how do you get the parameter information on URL without knowing?

The first uses the $_SERVER built-in array variable

$_SERVER['QUERY_STRING'] = $_SERVER['QUERY_STRING'] = $_SERVER['QUERY_STRING'] & sex=1
$_SERVER["REQUEST_URI"](return something like: / index.php? name=tank & sex=1)

Second, use pathinfo built-in functions



<?php
$test = pathinfo("http://localhost/index.php");
print_r($test);
/*
 The results are as follows 
Array
(
     [dirname] => http://localhost //url The path of the 
     [basename] => index.php  // Full file name 
     [extension] => php  // Filename suffix 
     [filename] => index // The file name 
)
*/
?>

Third, use parse_url built-in functions



<?php
$test = parse_url("http://localhost/index.php?name=tank&sex=1#top");
print_r($test);
/*
 The results are as follows 
Array
(
     [scheme] => http // What protocol to use 
     [host] => localhost // The host name 
     [path] => /index.php // The path 
     [query] => name=tank&sex=1 //  The parameter to be passed 
     [fragment] => top // The anchor point of the back root 
)
*/
?>

Fourth, use ES46en built-in functions



<?php
$test = basename("http://localhost/index.php?name=tank&sex=1#top");
echo $test;
/*
 The results are as follows 
index.php?name=tank&sex=1#top
*/
?>

In addition, there is their own regular matching processing to get the value of the need. This kind of way is more accurate, the efficiency temporarily does not consider...
The following extends the practice of regular processing:


<?php
preg_match_all("/(\w+=\w+)(#\w+)?/i","http://localhost/index.php?name=tank&sex=1#top",$match);
print_r($match);
/*
 The results are as follows 
Array
(
    [0] => Array
        (
            [0] => name=tank
            [1] => sex=1#top
        )
    [1] => Array
         (
            [0] => name=tank
             [1] => sex=1
         )
     [2] => Array
        (
             [0] =>
            [1] => #top
        )
)
*/
?>


It's a long way... Yet to be excavated...


Related articles: