Add Querystring Variable with Multiple Values PHP - php

I found a bit of code for stripping a query string and adding a new value to it, but I want to be able to do this with an array of options. Could someone give me a hand in modifying this code to do that?
Current code:
function add_querystring_var($url, $key, $value) {
$url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
$url = substr($url, 0, -1);
$value = $value ? "=".urlencode($value) : '';
if (strpos($url, '?') === false)
return ($url . '?' . $key . $value);
else
return ($url . '&' . $key . $value);
}
And I want it to do a foreach for each key and value given and then rebuild the new url.
Example: add_querystring_var(curPageURL(), array("order","sort"), array("swn","DESC"))
So I want the following URL http://www.example.com/students when put through the example above would return http://www.example.com/students?order=swn&sort=DESC
Does anyone know how I can do this? I'm new to this area of PHP. :)
UPDATE:
I forgot to mention sometimes the url may have other queries in it, so I want it to replace the ones that I enter into my array.
Example 1: http://www.example.com/students?page=2 would need to turn into http://www.example.com/students?page=2&order=swn&sort=DESC
Example 2: http://www.example.com/students?page=2&order=name&sort=ASC would need to turn into http://www.example.com/students?page=2&order=swn&sort=DESC

function add_querystring_var($url, $additions) {
$parsed = parse_url($url);
if (isset($parsed['query'])) {
parse_str($parsed['query'], $query);
} else {
$query = array();
}
$parsed['query'] = http_build_query(array_merge($query, $additions));
return http_build_url($parsed);
}
Use it this way:
$new_url = add_querystring_var($url, array('order' => 'swn', 'sort' => 'DESC'));
If you're getting errors saying that http_build_url is not defined, see
PHP http_build_url() and PECL Install

You're kind of reinventing the wheel with that function... first off, you'd be better off using urlencode() on your key/value data rather than that regular expression (and I see that you're not encoding your value string at all)
As dpDesignz mentions in his comment - there is a built-in function available: http_build_query()
$querydata = array('foo' => array('bar', 'baz'),
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
$querystring = http_build_query($data, '', '&');
Or, to use your example:
$querydata = array("order" => "swn", "sort" => "DESC");
$url = curPageURL();
$concat = "?";
if (strpos($url, "?") !== false)) {
$concat = "&"
}
$url .= $concat . http_build_query($data, '', '&');

Related

PHP: Get all parameters from the url without the file id

I want to extract all used parameters of a link as a text string. Example:
$link2 = http://example.com/index.html?song=abcdefg;
When using the above link $param should give out all the parameters '?song=abcdefg'. Unfortunately I do not know the id index.html nor the parameters and their respective data values.
As much as I am informed there is the function $_GET, which creates an array, but I need a string.
You can use parse_url:
$link2 = 'http://example.com/index.html?song=abcdefg';
$param = '?' . parse_url($link2, PHP_URL_QUERY);
echo $param;
// ?song=abcdefg
Many librairies exist to parse url, you can use this one for an exemple :
https://github.com/thephpleague/uri
use League\Uri\Schemes\Http as HttpUri;
$link2 = 'http://example.com/index.html?song=abcdefg';
$uri = HttpUri::createFromString($link2);
// then you can access the query
$query = $uri->query;
You also can try this one :
https://github.com/jwage/purl
A weird way to do this is
$link2 = 'http://example.com/index.html?song=abcdefg';
$param = strstr($link2, "?");
echo $param // ?song=abcdefg
strstr($link2, "?") will get everything after the first position of ?; including the leading ?
you can loop over the get array and parse it into a string:
$str = "?"
foreach ($_GET as $key => $value) {
$temp = $key . "=". $value . "&";
$str .= $temp
}
rtrim($str, "&")//remove leading '&'
You can use http_build_query() method
if ( isset ($_GET))
{
$params = http_build_query($_GET);
}
// echo $params should return "song=abcdefg";

preg_replace remove parameter variable

Want to remove p2variable from url string, below are 3 cases if case 3 also remove ? sign.
case 1: http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj
result: http://www.domain.com/myscript.php?p1=xyz&p3=ghj
case 2: http://www.domain.com/myscript.php?p2=10&p3=ghj
result: http://www.domain.com/myscript.php?p3=ghj
case 3: http://www.domain.com/myscript.php?p2=10
result: http://www.domain.com/myscript.php
Want to achieve result with single preg_replace expression.
Don't use regular expressions when dealing with URL values. It's much easier (and safer) to handle them as a URL instead of plain text.
This could be one way to do it:
Split the url first and parse the query string
Take the parameter out
Rebuild the url
The below code is an example of such an algorithm:
// remove $qs_key from query string of $url
// return modified url value
function clean_url_qs($url, $qs_key)
{
// first split the url in two parts (at most)
$parts = explode('?', $url, 2);
// check whether query string is passed
if (isset($parts[1])) {
// parse the query string into $params
parse_str($parts[1], $params);
// unset if $params contains $qs_key
if (array_key_exists($qs_key, $params)) {
// remove key
unset($params[$qs_key]);
// rebuild the url
return $parts[0] .
(count($params) ? '?' . http_build_query($params) : '');
}
}
// no change required
return $url;
}
Test code:
echo clean_url('http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj', 'p2'), "\n";
echo clean_url('http://www.domain.com/myscript.php?p2=10&p3=ghj', 'p2'), "\n";
echo clean_url('http://www.domain.com/myscript.php?p2=10', 'p2'), "\n";
Found this in one of my old projects (a bit of shitcode, but...), may help you:
$unwanted_param = 'p2';
$s = 'http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj';
$s = parse_url($s);
$params = explode('&', $s['query']);
$out_params = array();
foreach ($params as $key => &$param) {
list($name, $value) = explode('=', $param);
if ($unwanted_param == $name) {
unset($params[$key]);
} else {
$out_params[$name] = $value;
}
}
$query = '?' . http_build_query($out_params);
$result = $s['scheme'] . '://' . $s['host'] . $s['path'] . $query;
var_dump($result);
Using preg_replace, something like
$url = preg_replace('!([\?&]p2=[^&\?$]+)!i', '', $url);
However, personally I'd do the following
if (strpos($url, '?') !== false) {
list($domain, $qstring) = explode('?', $url, 2);
parse_str($qstring, $params);
if (isset($params['p2'])) {
unset($params['p2']);
}
$qstring = !empty($params) ? '?' . http_build_query($params) : '';
$url = $domain . $qstring;
}

How to remove the querystring and get only the URL?

I'm using PHP to build the URL of the current page. Sometimes, URLs in the form of
www.example.com/myurl.html?unwantedthngs
are requested. I want to remove the ? and everything that follows it (querystring), such that the resulting URL becomes:
www.example.com/myurl.html
My current code is this:
<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"] . ":" .
$_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
You can use strtok to get string before first occurence of ?
$url = strtok($_SERVER["REQUEST_URI"], '?');
strtok() represents the most concise technique to directly extract the substring before the ? in the querystring. explode() is less direct because it must produce a potentially two-element array by which the first element must be accessed.
Some other techniques may break when the querystring is missing or potentially mutate other/unintended substrings in the url -- these techniques should be avoided.
A demonstration:
$urls = [
'www.example.com/myurl.html?unwantedthngs#hastag',
'www.example.com/myurl.html'
];
foreach ($urls as $url) {
var_export(['strtok: ', strtok($url, '?')]);
echo "\n";
var_export(['strstr/true: ', strstr($url, '?', true)]); // not reliable
echo "\n";
var_export(['explode/2: ', explode('?', $url, 2)[0]]); // limit allows func to stop searching after first encounter
echo "\n";
var_export(['substr/strrpos: ', substr($url, 0, strrpos( $url, "?"))]); // not reliable; still not with strpos()
echo "\n---\n";
}
Output:
array (
0 => 'strtok: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'strstr/true: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'explode/2: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'substr/strrpos: ',
1 => 'www.example.com/myurl.html',
)
---
array (
0 => 'strtok: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'strstr/true: ',
1 => false, // bad news
)
array (
0 => 'explode/2: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'substr/strrpos: ',
1 => '', // bad news
)
---
Use PHP Manual - parse_url() to get the parts you need.
Edit (example usage for #Navi Gamage)
You can use it like this:
<?php
function reconstruct_url($url){
$url_parts = parse_url($url);
$constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];
return $constructed_url;
}
?>
Edit (second full example):
Updated function to make sure scheme will be attached and none notice msgs appear:
function reconstruct_url($url){
$url_parts = parse_url($url);
$constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . (isset($url_parts['path'])?$url_parts['path']:'');
return $constructed_url;
}
$test = array(
'http://www.example.com/myurl.html?unwan=abc',
`http://www.example.com/myurl.html`,
`http://www.example.com`,
`https://example.com/myurl.html?unwan=abc&ab=1`
);
foreach($test as $url){
print_r(parse_url($url));
}
Will return:
Array
(
[scheme] => http
[host] => www.example.com
[path] => /myurl.html
[query] => unwan=abc
)
Array
(
[scheme] => http
[host] => www.example.com
[path] => /myurl.html
)
Array
(
[scheme] => http
[host] => www.example.com
)
Array
(
[path] => example.com/myurl.html
[query] => unwan=abc&ab=1
)
This is the output from passing example URLs through parse_url() with no second parameter (for explanation only).
And this is the final output after constructing URL using:
foreach($test as $url){
echo reconstruct_url($url) . '<br/>';
}
Output:
http://www.example.com/myurl.html
http://www.example.com/myurl.html
http://www.example.com
https://example.com/myurl.html
best solution:
echo parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
No need to include your http://example.com in your <form action=""> if you're submitting a form to the same domain.
$val = substr( $url, 0, strrpos( $url, "?"));
Most Easiest Way
$url = 'https://www.youtube.com/embed/ROipDjNYK4k?rel=0&autoplay=1';
$url_arr = parse_url($url);
$query = $url_arr['query'];
print $url = str_replace(array($query,'?'), '', $url);
//output
https://www.youtube.com/embed/ROipDjNYK4k
You'll need at least PHP Version 5.4 to implement this solution without exploding into a variable on one line and concatenating on the next, but an easy one liner would be:
$_SERVER["HTTP_HOST"].explode('?', $_SERVER["REQUEST_URI"], 2)[0];
Server Variables: http://php.net/manual/en/reserved.variables.server.php
Array Dereferencing: https://wiki.php.net/rfc/functionarraydereferencing
You can use the parse_url build in function like that:
$baseUrl = $_SERVER['SERVER_NAME'] . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
You can try:
<?php
$this_page = basename($_SERVER['REQUEST_URI']);
if (strpos($this_page, "?") !== false) $this_page = reset(explode("?", $this_page));
?>
If you want to get request path (more info):
echo parse_url($_SERVER["REQUEST_URI"])['path']
If you want to remove the query and (and maybe fragment also):
function strposa($haystack, $needles=array(), $offset=0) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle, $offset);
if ($res !== false) $chr[$needle] = $res;
}
if(empty($chr)) return false;
return min($chr);
}
$i = strposa($_SERVER["REQUEST_URI"], ['#', '?']);
echo strrpos($_SERVER["REQUEST_URI"], 0, $i);
could also use following as per the php manual comment
$_SERVER['REDIRECT_URL']
Please note this is working only for certain PHP environment only and follow the bellow comment from that page for more information;
Purpose: The URL path name of the current PHP file, path-info is N/A
and excluding URL query string. Includes leading slash.
Caveat: This is before URL rewrites (i.e. it's as per the original
call URL).
Caveat: Not set on all PHP environments, and definitely only ones with
URL rewrites.
Works on web mode: Yes
Works on CLI mode: No
explode('?', $_SERVER['REQUEST_URI'])[0]
To remove the query string from the request URI, replace the query string with an empty string:
function request_uri_without_query() {
$result = $_SERVER['REQUEST_URI'];
$query = $_SERVER['QUERY_STRING'];
if(!empty($query)) {
$result = str_replace('?' . $query, '', $result);
}
return $result;
}
Because I deal with both relative and absolute URLs, I updated veritas's solution like the code below.
You can try yourself here: https://ideone.com/PvpZ4J
function removeQueryStringFromUrl($url) {
if (substr($url,0,4) == "http") {
$urlPartsArray = parse_url($url);
$outputUrl = $urlPartsArray['scheme'] . '://' . $urlPartsArray['host'] . ( isset($urlPartsArray['path']) ? $urlPartsArray['path'] : '' );
} else {
$URLexploded = explode("?", $url, 2);
$outputUrl = $URLexploded[0];
}
return $outputUrl;
}
Assuming you still want to get the URL without the query args (if they are not set), just use a shorthand if statement to check with strpos:
$request_uri = strpos( $_SERVER['REQUEST_URI'], '?' ) !== false ? strtok( $_SERVER["REQUEST_URI"], '?' ) : $_SERVER['REQUEST_URI'];
Try this
$url_with_querystring = 'www.example.com/myurl.html?unwantedthngs';
$url_data = parse_url($url_with_querystring);
$url_without_querystring = str_replace('?'.$url_data['query'], '', $url_with_querystring);
Try this:
$urrl=$_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME']
or
$urrl=$_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']

Manipulate a url string by adding GET parameters

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?
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.
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().
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
$queryString = http_build_query($data);
//$queryString = foo=bar&baz=boom&cow=milk&php=hypertext+processor
echo 'http://domain.com?'.$queryString;
//output: http://domain.com?foo=bar&baz=boom&cow=milk&php=hypertext+processor
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 ) );
}
Example with updating existent parameters.
Also url_encode used, and possibility to don't specify parameter value
<?
/**
* Add parameter to URL
* #param string $url
* #param string $key
* #param string $value
* #return string result URL
*/
function addToUrl($url, $key, $value = null) {
$query = parse_url($url, PHP_URL_QUERY);
if ($query) {
parse_str($query, $queryParams);
$queryParams[$key] = $value;
$url = str_replace("?$query", '?' . http_build_query($queryParams), $url);
} else {
$url .= '?' . urlencode($key) . '=' . urlencode($value);
}
return $url;
}
Use strpos to detect a ?. Since ? can only appear in the URL at the beginning of a query string, you know if its there get params already exist and you need to add params using &
function addGetParamToUrl(&$url, $varName, $value)
{
// is there already an ?
if (strpos($url, "?"))
{
$url .= "&" . $varName . "=" . $value;
}
else
{
$url .= "?" . $varName . "=" . $value;
}
}
<?php
$url1 = '/test?a=4&b=3';
$url2 = 'www.baidu.com/test?a=4&b=3&try_count=1';
$url3 = 'http://www.baidu.com/test?a=4&b=3&try_count=2';
$url4 = '/test';
function add_or_update_params($url,$key,$value){
$a = parse_url($url);
$query = $a['query'] ? $a['query'] : '';
parse_str($query,$params);
$params[$key] = $value;
$query = http_build_query($params);
$result = '';
if($a['scheme']){
$result .= $a['scheme'] . ':';
}
if($a['host']){
$result .= '//' . $a['host'];
}
if($a['path']){
$result .= $a['path'];
}
if($query){
$result .= '?' . $query;
}
return $result;
}
echo add_or_update_params($url1,'try_count',1);
echo "\n";
echo add_or_update_params($url2,'try_count',2);
echo "\n";
echo add_or_update_params($url3,'try_count',3);
echo "\n";
echo add_or_update_params($url4,'try_count',4);
echo "\n";
/**
* #example addParamToUrl('/path/to/?find=1', array('find' => array('search', 2), 'FILTER' => 'STATUS'))
* #example addParamToUrl('//example.com/path/to/?find=1', array('find' => array('search', 2), 'FILTER' => 'STATUS'))
* #example addParamToUrl('https://example.com/path/to/?find=1&FILTER=Y', array('find' => array('search', 2), 'FILTER' => 'STATUS'))
*
* #param $url string url
* #param array $addParams
*
* #return string
*/
function addParamToUrl($url, array $addParams) {
if (!is_array($addParams)) {
return $url;
}
$info = parse_url($url);
$query = array();
if ($info['query']) {
parse_str($info['query'], $query);
}
if (!is_array($query)) {
$query = array();
}
$params = array_merge($query, $addParams);
$result = '';
if ($info['scheme']) {
$result .= $info['scheme'] . ':';
}
if ($info['host']) {
$result .= '//' . $info['host'];
}
if ($info['path']) {
$result .= $info['path'];
}
if ($params) {
$result .= '?' . http_build_query($params);
}
return $result;
}
$parameters = array();
foreach ($get as $key => $value)
{
$parameters[] = $key.'='.$value;
}
$url = 'http://example.com/movies?'.implode('&', $parameters);
One-liner:
$url .= (strpos($url, '?') ? '&' : '?') . http_build_query($additionalParams);
using http_build_query is recommended because it encodes special characters (for example spaces or # in email addresses)
Improved version for 2022
This allows existing parameters to be replaced, and also preserves existing URL fragment (the part after # at the end of an URL)
function addParametersToUrl(string $url, array $newParams): string
{
$url = parse_url($url);
parse_str($url['query'] ?? '', $existingParams);
$newQuery = array_merge($existingParams, $newParams);
$newUrl = $url['scheme'] . '://' . $url['host'] . ($url['path'] ?? '');
if ($newQuery) {
$newUrl .= '?' . http_build_query($newQuery);
}
if (isset($url['fragment'])) {
$newUrl .= '#' . $url['fragment'];
}
return $newUrl;
}
Testing:
$newParams = [
'newKey' => 'newValue',
'existingKey' => 'new',
];
echo addParametersToUrl('https://www.example.com', $newParams);
// https://www.example.com?newKey=newValue&existingKey=new
echo addParametersToUrl('https://www.example.com/', $newParams);
// https://www.example.com/dir/?newKey=newValue&existingKey=new
echo addParametersToUrl('https://www.example.com/dir/', $newParams);
// https://www.example.com/dir/?newKey=newValue&existingKey=new
echo addParametersToUrl('https://www.example.com/dir/file?foo=bar', $newParams);
// https://www.example.com/dir/file?foo=bar&newKey=newValue&existingKey=new
echo addParametersToUrl('https://www.example.com/dir/file?foo=bar&existingKey=old', $newParams);
// https://www.example.com/dir/file?foo=bar&existingKey=new&newKey=newValue
echo addParametersToUrl('https://www.example.com/dir/file?foo=bar&existingKey=old#hash', $newParams);
// https://www.example.com/dir/file?foo=bar&existingKey=new&newKey=newValue#hash
echo addParametersToUrl('https://www.example.com/dir/file#hash', $newParams);
// https://www.example.com/dir/file?newKey=newValue&existingKey=new#hash
echo addParametersToUrl('https://www.example.com/dir/file?foo=bar#hash', $newParams);
// https://www.example.com/dir/file?foo=bar&newKey=newValue&existingKey=new#hash
I think you should do it something like this.
class myURL {
protected $baseURL, $requestParameters;
public function __construct ($newURL) {
$this->baseurl = $newURL;
$this->requestParameters = array();
}
public function addParameter ($parameter) {
$this->requestParameters[] = $parameter;
}
public function __toString () {
return $this->baseurl.
( count($this->requestParameters) ?
'?'.implode('&', $this->requestParameters) :
''
);
}
}
$url1 = new myURL ('http://www.acme.com');
$url2 = new myURL ('http://www.acme.com');
$url2->addParameter('sort=popular');
$url2->addParameter('category=action');
$url1->addParameter('category=action');
echo $url1."\n".$url2;
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 "&"
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;
}
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;
}
Try this function to add URL parameters.
Then you can disable the link when parameter is set so there is no url parameter duplicate.
<?php
function addQueryString($a)
{
if (empty($_SERVER['QUERY_STRING']))
return '?' . $a;
else if (!empty($_SERVER['QUERY_STRING']))
return '?' . $_SERVER['QUERY_STRING'] . '&' . $a;
}
?>
test
sat
In case you are using WordPress you can simply use
add_query_args(['sort' => 'asc'], 'http:/example.com/?search=news')
Docs https://developer.wordpress.org/reference/functions/add_query_arg/

PHP: Replace 1st char in a string - to create a link to itself

In my test.php I would like to provide a link back to the production script index.php, passing the same GET-parameters:
foreach ($_GET as $key => $val) {
$get .= "&$key=$val";
}
# this one is wrong - I want to replace just the first "&"
$get = str_replace("&", "?", $get);
echo '<p>You are viewing the test version.</p>
<p><a href="/index.php' . $get .
'">Return to production version</a></p>';
How do I replace just the 1st char in the $get string?
Or maybe there is a nicer way to create a "self-link"?
You could just do:
$get = 'index.php?' . $_SERVER['QUERY_STRING'];
$get = preg_replace('/&/', '?', $get, 1);
You should look at $_SERVER['QUERY_STRING'], which contains the query string from the request, except for the first ? charater.
So, for instance, if you were to go to http://example.com/page.php?var1=val1&var2=val2, the contents of $_SERVER['QUERY_STRING'] would be var1=val1&var2=val2
Also, to replace the first character of the string, you can simply use:
if(strlen($string) > 0) // Unexpected behavior would occur with empty strings
{
$string[0] = '?'; // This would modify the first character of a string
}
$get = "";
foreach ($_GET as $key => $val) {
$get .= "&$key=$val";
}
if(strlen($get) > 0)
$get[0] = "?";

Categories