Assume this is my current URL:
http://example.com/search?param1=foo¶m2=bar
Now I want to add param3=baz. So this is the code:
<a href="?param3=baz" >add param3</a>
//=> http://example.com/search?param3=baz
See? param1 and param2 will be removed. So I have to handle it like this:
<?php
$query_str = parse_url($url, PHP_URL_QUERY);
parse_str($query_str, $query_params);
$query_params = $query_params == '' ? '?' : $query_params . '&';
?>
<a href="?{$query_params}param3=baz" >add param3</a>
Seems ugly, but ok, nevermind. Now what happens if a parameter be already exist and I need to edit it? Assume this example:
http://example.com/search?param1=foo¶m2=bar
Now how can I make a link which edits the value of parame2? (plus keeping other parameters)
You can use function http_build_query to generate new query, like this:
$url = 'http://example.com/search?param1=foo¶m2=bar';
$query_str = parse_url($url, PHP_URL_QUERY);
parse_str($query_str, $params);
$data = [
'param3' => 'baz'
];
$params = array_merge($params, $data);
echo http_build_query($params) . "\n";
And output will be:
param1=foo¶m2=bar¶m3=baz
I use array_merge for override exist params, if we get url:
$url = 'http://example.com/search?param1=foo¶m3=bar';
The same code output will be:
param1=foo¶m3=baz
We override exist param and save old params.
There is no way to write a relative URI that preserves the existing query string while adding additional parameters to it.
You have to Do again:
search?param1=foo¶m=bar¶m3=baz
Or
Using Javascript is Possible
How to add a parameter to the URL?
Or
function currentUrl() {
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['SCRIPT_NAME'];
$params = $_SERVER['QUERY_STRING'];
return $protocol . '://' . $host . $script . '?' . $params;
}
Then add your value with something like;
echo currentUrl().'¶m3=baz';
or
Whatever GET parameters you had will still be there and if param3 was a
parameter before it will be overwritten, otherwise it will be included
at the end.
http_build_query(array_merge($_GET, array("param3"=>"baz")))
Related
I'm trying to generate an URL from all values of two arrays by using http_build_query:
Array 1:
$server = array($_GET["server"]);
Array 2:
$data = array($_GET["z_koord"],
$_GET['x_koord'],
$_GET["y_koord"],);
The code for generating URL I currently have written:
$server = array(''=>$_GET["server"]);
$data = array($_GET["z_koord"],
$_GET['x_koord'],
$_GET["y_koord"],);
$url = '.tile.openstreetmap.org';
$saite = http_build_query($server). $url ."/". http_build_query($data,'','/').".png";
Here's the URL made of code above:
=c.tile.openstreetmap.org/0=6/1=90/2=110.png
Here's the structure of url I'm trying to make:
c.tile.openstreetmap.org/6/90/110.png
I have reviewed some other posts about this topic like this one and this, but those posts aren't completely useful for solving my problem.
So I hope someone with greater knowledge could show me a solution or at least a hint how to get closer to solution.
You could use implode():
$server = $_GET["server"];
$data = [$_GET["z_koord"],
$_GET['x_koord'],
$_GET["y_koord"]];
$url = '.tile.openstreetmap.org';
$saite = "$server/$url/" . implode('/', $data) . ".png";
I'm not sure about some things in this code, but the implode() should do the job.
You are using http_build_query in the wrong way. You just don't need that. There are 2 options, you may use any one of them.
Use implode(), the simplest way to do the job.
$server = array(
'' => $_GET['server']
);
$data = array(
$_GET['z_koord'],
$_GET['x_koord'],
$_GET['y_koord'],
);
$url = $server . '.tile.openstreetmap.org';
$saite = $url . '/' . implode("/", $data) . '.png';
Directly create the URL using the Parameters as shown here:
$url = '.tile.openstreetmap.org' .;
$saite = $_GET['server'] . $url . '/' . $_GET['z_koord'] .'/'. $_GET['x_koord'] . '/'.$_GET['y_koord'] . '.png';
I want to check a parameter in a url variable, for example:
$var2join = 'en'; // can be anything else
$url = 'https://www.example.com/hello/parameter2';
$url2 = 'https://www.example.com/hello2';
$url3 = 'https://www.example.com/en/hey';
first check if the $url vars have the $var2join into $var as parameter if have it, leave it intact and if not add it.
Wanted output:
$url = 'https://www.example.com/en/hello/parameter2';
$url2 = 'https://www.example.com/en/hello2';
$url3 = 'https://www.example.com/en/hey';
I tried:
$url = (!preg_match('~^/[a-z]{2}(?:/|$)~', $location)) ? '/' . $var2join . $url : $url;
Use parse_url(), it is specifically for analysing URLs and their various elements.
Note this code assumes your parameters are path segments, as you describe above. If you ever use query string parameters like ?foo=bar, you'd need to adjust.
$var2join = 'en';
$url = 'https://www.example.com/hello/parameter2';
// Split URL into each of its parts
$url_parts = parse_url($url);
// Create an array of all the path parts, which correspond to
// parameters in your scheme
$params = explode('/', $url_parts['path']);
// Check if your var is in there
if (!in_array($var2join, $params)) {
// If not, reconstruct the same URL, but with your var inserted.
// NOTE this assumes a pretty simple URL, you'll need to adjust if
// you ever have other elements like port number, u/p, query strings
// etc. #Jason-rush links to something in the PHP docs to handle
// such cases.
$url = $url_parts['scheme'] . '://' . $url_parts['host'] . '/' . $var2join . $url_parts['path'];
}
// Check your result - https://www.example.com/en/hello/parameter2
echo $url;
This is a little generic function with some support code to give you some ideas... Not very elegant but it works.
<?php
$base_url = 'https://www.example.com/';
$var2join = 'en'; // can be anything else
$url = $base_url . 'hello/parameter2';
$url2 = $base_url . 'hello2';
$url3 = $base_url . 'en/hey';
$url4 = $base_url . 'hey/this/is/longer';
echo prepend_path_to_url($base_url, $url, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url2, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url3, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url4, $var2join);
echo '<br>';
/**
* Prepend a Path to the url
*
* #param $base_url
* #param $url
* #param $path_to_join
* #return string
*/
function prepend_path_to_url($base_url, $url, $path_to_join) {
// Does the path_to_join exist in the url
if (strpos($url, $path_to_join) === FALSE) {
$url_request = str_replace($base_url,'',$url);
$url = $base_url . $path_to_join . '/'. $url_request;
}
return $url;
}
I have to add a GET variable to a url. But the URL might already have GET variables. What's the most efficient way to add this new variable?
Example URLs:
http://domain.com/
http://domain.com/index.html?name=jones
I need to add: tag=xyz:
http://domain.com/?tag=xyz
http://domain.com/index.html?name=jones&tag=xyz
What's the most efficient way to know whether to prepend my string with a ? or &?
Here's a version of the function I have so far:
// where arrAdditions looks like array('key1'=>'value1','key2'=>'value2');
function appendUrlQueryString($url, $arrAdditions) {
$arrQueryStrings = array();
foreach ($arrAdditions as $k=>$v) {
$arrQueryStrings[] = $k . '=' . $v;
}
$strAppend = implode('&',$arrQueryStrings);
if (strpos($url, '?') !== false) {
$url .= '&' . $strAppend;
} else {
$url = '?' . $strAppend;
}
return $url;
}
But, is simply looking for the ? in the existing url problematic? For example, is it possible that a url includes a ? but not actual queries, perhaps as an escaped character?
Take a look at PHP PECL's http_build_url. Said by the doc page:
Build a URL.
The parts of the second URL will be merged into the first according to the flags argument.
Addition:
If you don't have PECL installed, we can jump through some hoops. This approach is somewhat solid right up until we try to rebuild the new URL. Stock PHP (minus PECL) doesn't have a reverse of parse_url(). Making it harder, parse_url() removes some of the grammar from a URL in the resulting parts array so we have to put them back in when we reassemble. http_build_url() can take care of this for us, but if it were available, you wouldn't be reading this portion as it's what I originally recommended. Anyway, here's that code:
<?php
/**
* addQueryParam - given a URL and some new params for its query string, return the modified URL
*
* #see http://us1.php.net/parse_url
* #see http://us1.php.net/parse_str
* #throws Exception on bad input
* #param STRING $url A parseable URL to add query params to
* #param MIXED $input_query_vars - STRING of & separated pairs of = separated key values OR ASSOCIATIVE ARRAY of STRING keys => STRING values
* #return STRING new URL
*/
function addQueryParam ($url, $input_query_vars) {
// Parse new parameters
if (is_string($input_query_vars)) {
parse_str($input_query_vars, $input_query_vars);
}
// Ensure array of parameters now available
if (!is_array($input_query_vars)) {
throw new Exception(__FUNCTION__ . ' expects associative array or query string as second parameter.');
}
// Break up given URL
$url_parts = parse_url($url);
// Test for proper URL parse
if (!is_array($url_parts)) {
throw new Exception(__FUNCTION__ . ' expects parseable URL as first parameter');
}
// Produce array of original query vars
$original_query_vars = array();
if (isset($url_parts['query']) && $url_parts['query'] !== '') {
parse_str($url_parts['query'], $original_query_vars);
}
// Merge new params inot original
$new_query_vars = array_merge($original_query_vars, $input_query_vars);
// replace the original query string
$url_parts['query'] = http_build_query($new_query_vars);
// Put URL grammar back in place
if (!empty($url_parts['scheme'])) {
$url_parts['scheme'] .= '://';
}
if (!empty($url_parts['query'])) {
$url_parts['query'] = '?' . $url_parts['query'];
}
if (!empty($url_parts['fragment'])) {
$url_parts['fragment'] = '#' . $url_parts['fragment'];
}
// Put it all back together and return it
return implode('', $url_parts);
}
// Your demo URLs
$url1 = 'http://domain.com/';
$url2 = 'http://domain.com/index.html?name=jones';
//Some usage (I did this from CLI)
echo $url1, "\n";
echo addQueryParam($url1, 'tag=xyz'), "\n";
echo addQueryParam($url1, array('tag' => 'xyz')), "\n";
echo $url2, "\n";
echo addQueryParam($url2, 'tag=xyz'), "\n";
echo addQueryParam($url2, array('tag' => 'xyz')), "\n";
echo addQueryParam($url2, array('name' => 'foo', 'tag' => 'xyz')), "\n";
To check if parameter already exists you could try parse_str().
This will parse your URL and put variables into an array.
It will give you some issues if you will pass full URL:
$url = "http://domain.com/index.html?name=jones&tag=xyz";
parse_str($url', $arr);
print_r($arr);
will give you
Array ( [http://domain_com/index_html?name] => jones [tag] => xyz )
but with
$url = "name=jones&tag=xyz";
you will get
Array ( [name] => jones [tag] => xyz )
You could explode full URL by '?' and check the second part. After the check you could know how to modify your URL. But I'm not sure this would work all the time.
$url_one = "http://www.stackoverflow.com?action=submit&id=example";
$new_params = "user=john&pass=123";
$final_url = $url_one."&".$new_param
s;
Now $final_url has old url and new params added to it.
Example:
$url = http://example.com/?arg=val&arg2=test&arv3=testing&arv2=val2
remove_url_arg($url, "arg2")
echo($url); // http://example.com/?arg=val&arv3=testing
The above remove_url_arg() function removes all occurrence of arg2 argument from the URL
unset($_GET['arg2']);
$query_string = http_build_query($_GET);
if it's not on request but to parse whole url
$parsed = parse_url($url);
$qs_arr = parse_str($parsed['query'],1);
unset($qs_arr['arg2']);
$parsed['query'] = http_build_query($qs_arr);
and then assemble the url back.
or one-liner regexp
I have a question, How I can add another get variable in my current url
book.php?action=addressbook
i want to add
book.php?action=addressbook&page=2
how to generate hyperlink for this, i have tried it using $_SERVER['PHP_SELF'] but query string are not included in url its showing something like that
book.php?page=2
I want to append my other variables to query string
Please help
You can also use http_build_query(); to append more params to your URL
$params = $_GET;
$params["item"] = 45;
$new_query_string = http_build_query($params);
for instance:
$data = array('page'=> 34,
'item' => 45);
echo http_build_query($data); //page=34&item=45
or include amp
echo http_build_query($data, '', '&'); //page=34&&item=45
$get = $_GET;
$get['page'] = 2;
echo 'Page 2';