Manipulate a url string by adding GET parameters

前端 未结 15 2101
旧巷少年郎
旧巷少年郎 2020-11-29 00:50

I want to add GET parameters to URLs that may and may not contain GET parameters without repeating ? or &.

Example:

If I want t

相关标签:
15条回答
  • 2020-11-29 01:08

    another improved function version. Mix of existing answers with small improvements (port support) and bugfixes (checking keys properly).

    /**
     * @param string $url original url to modify - can be relative, partial etc
     * @param array $paramsOverride associative array, can be empty
     * @return string modified url
     */
    protected function overrideUrlQueryParams($url, $paramsOverride){
        if (!is_array($paramsOverride)){
            return $url;
        }
    
        $url_parts = parse_url($url);
    
        if (isset($url_parts['query'])) {
            parse_str($url_parts['query'], $params);
        } else {
            $params = [];
        }
    
        $params = array_merge($params, $paramsOverride);
    
        $res = '';
    
        if(isset($url_parts['scheme'])) {
            $res .= $url_parts['scheme'] . ':';
        }
    
        if(isset($url_parts['host'])) {
            $res .= '//' . $url_parts['host'];
        }
    
        if(isset($url_parts['port'])) {
            $res .= ':' . $url_parts['port'];
        }
    
        if (isset($url_parts['path'])) {
            $res .= $url_parts['path'];
        }
    
        if (count($params) > 0) {
            $res .= '?' . http_build_query($params);
        }
    
        return $res;
    }
    
    0 讨论(0)
  • 2020-11-29 01:10

    Basic method

    $query = parse_url($url, PHP_URL_QUERY);
    
    // Returns a string if the URL has parameters or NULL if not
    if ($query) {
        $url .= '&category=1';
    } else {
        $url .= '?category=1';
    }
    

    More advanced

    $url = 'http://example.com/search?keyword=test&category=1&tags[]=fun&tags[]=great';
    
    $url_parts = parse_url($url);
    // If URL doesn't have a query string.
    if (isset($url_parts['query'])) { // Avoid 'Undefined index: query'
        parse_str($url_parts['query'], $params);
    } else {
        $params = array();
    }
    
    $params['category'] = 2;     // Overwrite if exists
    $params['tags'][] = 'cool';  // Allows multiple values
    
    // Note that this will url_encode all values
    $url_parts['query'] = http_build_query($params);
    
    // If you have pecl_http
    echo http_build_url($url_parts);
    
    // If not
    echo $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'] . '?' . $url_parts['query'];
    

    You should put this in a function at least, if not a class.

    0 讨论(0)
  • 2020-11-29 01:12

    This function overwrites an existing argument

    function addToURL( $key, $value, $url) {
        $info = parse_url( $url );
        parse_str( $info['query'], $query );
        return $info['scheme'] . '://' . $info['host'] . $info['path'] . '?' . http_build_query( $query ? array_merge( $query, array($key => $value ) ) : array( $key => $value ) );
    }
    
    0 讨论(0)
  • 2020-11-29 01:13
     public function addGetParamToUrl($url, $params)
    {
        foreach ($params as $param) {
             if (strpos($url, "?"))
            {
                $url .= "&" .http_build_query($param); 
            }
            else
            {
                $url .= "?" .http_build_query($param); 
            }
        }
        return $url;
    }
    
    0 讨论(0)
  • 2020-11-29 01:15

    Here's a shorter version of the accepted answer:

    $url .= (parse_url($url, PHP_URL_QUERY) ? '&' : '?') . 'category=action';
    

    Edit: as discussed in the accepted answer, this is flawed in that it doesn't check to see if category already exists. A better solution would be to treat the $_GET for what it is - an array - and use functions like in_array().

    0 讨论(0)
  • 2020-11-29 01:18

    After searching for many resources/answers on this topic, I decided to code my own. Based on @TaylorOtwell's answer here, this is how I process incoming $_GET request and modify/manipulate each element.

    Assuming the url is: http://domain.com/category/page.php?a=b&x=y And I want only one parameter for sorting: either ?desc=column_name or ?asc=column_name. This way, single url parameter is enough to sort and order simultaneously. So the URL will be http://domain.com/category/page.php?a=b&x=y&desc=column_name on first click of the associated table header row.

    Then I have table row headings that I want to sort DESC on my first click, and ASC on the second click of the same heading. (Each first click should "ORDER BY column DESC" first) And if there is no sorting, it will sort by "date then id" by default.

    You may improve it further, like you may add cleaning/filtering functions to each $_GET component but the below structure lays the foundation.

    foreach ($_GET AS $KEY => $VALUE){
        if ($KEY == 'desc'){
            $SORT = $VALUE;
            $ORDER = "ORDER BY $VALUE DESC";
            $URL_ORDER = $URL_ORDER . "&asc=$VALUE";
        } elseif ($KEY == 'asc'){
            $SORT = $VALUE;
            $ORDER = "ORDER BY $VALUE ASC";
            $URL_ORDER = $URL_ORDER . "&desc=$VALUE";
        } else {
            $URL_ORDER .= "&$KEY=$VALUE";
            $URL .= "&$KEY=$VALUE";
        }
    }
    if (!$ORDER){$ORDER = 'ORDER BY date DESC, id DESC';}
    if ($URL_ORDER){$URL_ORDER = $_SERVER[SCRIPT_URL] . '?' . trim($URL_ORDER, '&');}
    if ($URL){$URL = $_SERVER[SCRIPT_URL] . '?' . trim($URL, '&');}
    

    (You may use $_SERVER[SCRIPT_URI] for full URL beginning with http://domain.com)

    Then I use resulting $ORDER I get above, in the MySQL query:

    "SELECT * FROM table WHERE limiter = 'any' $ORDER";
    

    Now the function to look at the URL if there is a previous sorting and add sorting (and ordering) parameter to URL with "?" or "&" according to the sequence:

            function sort_order ($_SORT){
                global $SORT, $URL_ORDER, $URL;
                if ($SORT == $_SORT){
                    return $URL_ORDER;
                } else {
                    if (strpos($URL, '?') !== false){
                        return "$URL&desc=$_SORT";
                    } else {                        
                        return "$URL?desc=$_SORT";
                    }
                }
            }
    

    Finally, the table row header to use the function:

            echo "<th><a href='".sort_order('id')."'>ID</a></th>";
    

    Summary: this will read the URL, modify each of the $_GET components and make the final URL with parameters of your choice with the correct form of usage of "?" and "&"

    0 讨论(0)
提交回复
热议问题