how to read query string from a URL in PHP

前端 未结 3 2003
慢半拍i
慢半拍i 2021-01-24 14:26

If the URL is https://www.mohsin.com?main=17&street=71, then what is the PHP code to grab the \"main\" and \"street\" values?

I am expecting line of codes written in

相关标签:
3条回答
  • 2021-01-24 15:00

    Just call the following function:

    function getQueryParameter($url, $param) {
        $parsedUrl = parse_url($url);
        if (array_key_exists('query', $parsedUrl)) {
            parse_str($parsedUrl['query'], $queryParameters);
            if (array_key_exists($param, $queryParameters)) {
                return $queryParameters[$param];
            }
        }
    }
    

    Example:

    • $parameter = getQueryParameter('https://www.mohsin.com?main=17&street=71', 'main') will return 17.
    • $parameter = getQueryParameter('https://www.mohsin.com?main=17&street=71', 'street') will return 71.
    • $parameter = getQueryParameter('https://www.mohsin.com?main=17&street=71', 'invalid') will return null.
    0 讨论(0)
  • 2021-01-24 15:01

    $main = $_GET['main'] will get the main variable and $street = $_GET['street'] will get the street variable. All URL parameters are loaded into the PHP $_GET super global array and the super global is an associative array.

    0 讨论(0)
  • 2021-01-24 15:02

    Please Try with this :

    <?php
        $main = $_GET['main'];
        $street = $_GET['street'];
    ?>
    
    0 讨论(0)
提交回复
热议问题