Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulate a url string by adding GET parameters

Tags:

string

url

php

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

Example:

If I want to add category=action

$url="http://www.acme.com";  // will add ?category=action at the end  $url="http://www.acme.com/movies?sort=popular";  // will add &category=action at the end 

If you notice I'm trying to not repeat the question mark if it's found.

The URL is just a string.

What is a reliable way to append a specific GET parameter?

like image 275
CodeOverload Avatar asked Apr 27 '11 19:04

CodeOverload


People also ask

How do you pass string parameters in GET request URL?

Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".

What is get parameter in URL?

GET parameters (also called URL parameters or query strings) are used when a client, such as a browser, requests a particular resource from a web server using the HTTP protocol. These parameters are usually name-value pairs, separated by an equals sign = . They can be used for a variety of things, as explained below.

How can the parameters in a URL be edited?

Edit / Update a Parameter The value of a parameter can be updated with the set() method of URLSearchParams object. After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.


1 Answers

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.

like image 51
andrewtweber Avatar answered Sep 21 '22 03:09

andrewtweber