- How to Pass an Array in URL Query String with PHP
- Passing a Simple Array within http_build_query()
- Passing an Indexed Array within http_build_query()
- Passing a Multidimensional Array within http_build_query()
- Describing Query String
- Add a set of querystring params to a URL
- Appending query strings to URL
- Add a set of querystring params to a URL
- How to append all urls in a string with query builder url parameters?
- Добавить get к строке
- 6 ответов 6
How to Pass an Array in URL Query String with PHP
PHP includes the http_build_query() method for creating URL encoded query string. This method is available only on PHP 5 and above versions. In this snippet, you will learn how to pass an array in URL query string using PHP.
The syntax of http_build_query() will look as follows:
http_build_query($query, $numeric_prefix, $separator, $encoded_type)
Passing a Simple Array within http_build_query()
In this section, we are going to use $vars array for generating the URL query string. The $vars array includes the data of search keyword, as well as the page number.
Let’s see an example where this array is passed to the http_build_query() method for generating a query string:
$vars = ['page' => 26, 'search' => 'w3docs']; $qs = http_build_query($vars); $url = 'http://www.example.com/search.php?' . $qs; echo $url; ?>
The code, represented above will return the following url query string:
http://www.example.com/search.php?page=26&search=w3docs
Passing an Indexed Array within http_build_query()
Now, let’s see an example where $vars is an indexed array that comprises an employee data:
$vars = ['employee', 'brown', 'developer', 'emp_id' => '332']; $qs = http_build_query($vars); $url = 'http://www.example.com/search.php?' . $qs; echo $url; ?>
The code above will return the following url query string:
http://www.example.com/search.php?0=employee&1=brown&2=developer&emp_id=332
Passing a Multidimensional Array within http_build_query()
In this section, we will consider $vars as a multidimensional array with employee data. Once passing through the http_build_query() method, it will return a complex url query string.
$vars = ['employee' => ['name' => 'Brown', 'age' => 41, 'dept' => 'IT', 'dob' => '9/22/1980'], 'role' => ['engineer', 'developer']]; $qs = http_build_query($vars); $url = 'http://www.example.com/search.php?' . $qs; echo $url; ?>
This code will return the following url query string:
http://www.example.com/search.php?employee%5Bname%5D=Brown&employee%5Bage%5D=39&employee%5Bdept%5D=IT&employee%5Bdob%5D=9%2F22%2F1980&role%5B0%5D=engineer&role%5B1%5D=developer
Describing Query String
The query string term is considered a part of Uniform Resource Locator (URL). It is in the form of a series of key-value pairs. Generally, it is used for creating a typical url or getting data from URL.
So, you can use the query string for different purposes such as search keywords, url building, specific web page tracking, and many more.
Add a set of querystring params to a URL
(ideone) Solution 2: I use this in my pagination script to append query strings to the (page number) query, this enables me to sort a table from the same page or set the in a table populated by Usage: You can use it in a href: Solution: As you can see on the manual page here http://php.net/parse_str the parse_str function doesn’t return the array of values, it writes it to the second parameter and returns void always. Solution 2: If links are built with PHP, just append the original query string to them: In JavaScript, just append the value of to all the links you need to ‘pass’ the query string.
Appending query strings to URL
These appendages you ask about is the actual so called query part of an URI:
://? foo://example.com:8042/over/there?name=ferret#nose \_/ \______________/\_________/ \_________/ \__/ | | | | | scheme authority path query fragment
Taken from: 3. Syntax Components (RFC 3986) https://www.rfc-editor.org/rfc/rfc3986#page-16
You then need a helper function that is append the (optional) to an existing :// part. I ignore the for this exmaple, as it would needed to be added at the end and I want to leave something as an exercise:
function href_append_query($href) < $query = isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '' ; $query = strtr( $query, [ '"' =>'"', "'" => ''', '&' => '&' ] ); return $href . $query; >
This little function will ensure that the exisitng QUERY_STRING which can be obtained via $_SERVER Docs is encoded for HTML output.
If links are built with PHP, just append the original query string to them:
In JavaScript, just append the value of window.location.search to all the links you need to ‘pass’ the query string.
You could also use js/jquery to append the existing query string to each link on the page:
$(function() < $('a').each(function() < link = $(this).attr('href'); query = window.location.search; if (link.indexOf('?') !== -1 && query !== '') < query = query.replace('?','&'); >$(this).attr('href',link+query); >); >);
PHP: Adding parameters to a url?, Basically, we use http_build_query() to take everything in $_GET, and merge it with an array of any other parameters we want. In this example, I just create an array on the fly, using your example parameter. Usage examplehttp_build_query(array_merge($_GET, array(‘newvar’=>’123’)))Feedback
Add a set of querystring params to a URL
- Your code is very spaced out. It doesn’t need to be.
- Consider using industry-standard style by using Egyptian braces for control structures like if and foreach .
- Get rid of the $http_host variable; you never use it.
- Consider generalising your function to accept any URL instead of pulling REQUEST_URI .
- You’re kind of reinventing the wheel; PHP has the built-in functions parse_str and http_build_query that you can use.
- Do you intend to replace existing variables, or just to append them to the request?
Here’s an example that takes advantage of the built-in functions, and intelligently merges in conflicts. (ideone)
/** * Like array_merge, but will recursively merge array values. * * @param array $a1 * The array to be merged into. * @param array $a2 * The array to merge in. Overwrites $a1, when string keys conflict. * Numeric keys will just be appended. * @return array * The array, post-merge. */ function merge_query_var_arrays($a1, $a2) < foreach ($a2 as $k2 =>$v2) if (is_string($k2)) $a1[$k2] = isset($a1[$k2]) && is_array($v2) ? merge_query_var_arrays($a1[$k2], $v2) : $v2; else $a1[] = $v2; return $a1; > /** * @param string $query_string * The URL or query string to add to. * @param string|array $vars_to_add * Either a string in var=val&[. ] format, or an array. * @return string * The new query string. Duplicate vars are overwritten. */ function add_query_vars($query_string, $vars_to_add) < if (is_string($vars_to_add)) parse_str($vars_to_add, $vars_to_add); if (preg_match('/.*\?/', $query_string, $match)) $query_string = preg_replace('/.*\?/', '', $query_string); parse_str($query_string, $query_vars); $query_vars = merge_query_var_arrays($query_vars, $vars_to_add); return @$match[0] . http_build_query($query_vars); >
I use this function in my pagination script to append query strings to the ?p= (page number) query, this enables me to sort a table from the same page or set the Limit in a table populated by MySQL
public function modQuery($add_to, $rem_from = array(), $clear_all = false)< if ($clear_all)< $query_string = array(); >else < parse_str($_SERVER['QUERY_STRING'], $query_string); >if (!is_array($add_to)) < $add_to = array(); >$query_string = array_merge($query_string, $add_to); if (!is_array($rem_from)) < $rem_from = array($rem_from); >foreach($rem_from as $key) < unset($query_string[$key]); >return http_build_query($query_string); >
Php — append query string to any form of URL, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams
How to append all urls in a string with query builder url parameters?
As you can see on the manual page here http://php.net/parse_str the parse_str function doesn’t return the array of values, it writes it to the second parameter and returns void always. You would have called array_merge on a single array anyway. So you can take your existing line:
$gets = isset($url['query']) ? array_merge(parse_str($url['query'])) : $add;
and replace it with something like:
$params = array(); if (isset($url['query'])) < parse_str($url['query'], $params); >$gets = array_merge($params, $add);
In the end you will get something like this: http://codepad.org/5VIEcAWy
Php — Manipulate a url string by adding GET parameters, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams
Добавить get к строке
6 ответов 6
$add = 'lang=ru'; $url = (isset($_SERVER["QUERY_STRING"])? '&' : '?'; $url.=$add;
ну тут любое решение будут одни и те же яйца ))) просто strpos будет медленнее, чем просто проверить наличие
Я вот такую функцию использую. Работает дольше Вашего варианта, но зато в строке не будет повторяющихся параметров.
/** z_add_url_get * * @param $a_data - массив с данными которые должны быть добавлены к строке * @param $url - адрес страницы, если false то берется текущтй url * * **/ function z_add_url_get($a_data,$url = false) < $http = $_SERVER['HTTPS'] ? 'https':'http'; if($url === false)< $url = $http.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; >$query_str = parse_url($url); $path = !empty($query_str['path']) ? $query_str['path'] : ''; $return_url = $query_str['scheme'].'://'.$query_str['host'].$path; $query_str = !empty($query_str['query']) ? $query_str['query'] : false; $a_query = array(); if($query_str) < parse_str($query_str,$a_query); >$a_query = array_merge($a_query,$a_data); $s_query = http_build_query($a_query); if($s_query) < $s_query = '?'.$s_query; >return $return_url.$s_query; > $url = 'http://z-site.ru/?my_param=hello&my_param_2=bye'; echo z_add_url_get(array('my_param_2'=>'goodbye','new_param'=>'this is new param'),$url); // http://z-site.ru/?my_param=hello&my_param_2=goodbye&new_param=this+is+new+param $url = 'http://z-site.ru/'; echo z_add_url_get(array('my_param_2'=>'goodbye','new_param'=>'this is new param'),$url); // http://z-site.ru/?my_param_2=goodbye&new_param=this+is+new+param