php; remove single variable value pair from querystring - php

I have a page that lists out items according to numerous parameters ie variables with values.
listitems.php?color=green&size=small&cat=pants&pagenum=1 etc.
To enable editing of the list, I have a parameter edit=1 which is appended to the above querystring to give:
listitems.php?color=green&size=small&cat=pants&pagenum=1&edit=1
So far so good.
WHen the user is done editing, I have a link that exits edit mode. I want this link to specify the whole querystring--whatever it may be as this is subject to user choices--except remove the edit=1.
When I had only a few variables, I just listed them out manually in the link but now that there are more, I would like to be able programmatically to just remove the edit=1.
Should I do some sort of a search for edit=1 and then just replace it with nothing?
$qs = str_replace("&edit=1, "", $_SERVER['QUERY_STRING']);
<a href='{$_SERVER['PHP_SELF']}?{$qs}'>return</a>;
Or what would be the cleanest most error-free way to do this.
Note: I have a similar situation when going from page to page where I'd like to take out the pagenum and replace it with a different one. There, since the pagenum varies, I cannot just search for pagenum=1 but would have to search for pagenum =$pagenum if that makes any difference.
Thanks.

I'd use http_build_query, which nicely accepts an array of parameters and formats it correctly. You'd be able to unset the edit parameter from $_GET and push the rest of it into this function.
Note that your code has a missing call to htmlspecialchars(). A URL can contain characters that are active in HTML. So when outputting it into a link: Escape!
Some example:
unset($_GET['edit']); // delete edit parameter;
$_GET['pagenum'] = 5; // change page number
$qs = http_build_query($_GET);
... output link here.

Here's my shot:
/**
* Receives a URL string and a query string to remove. Returns URL without the query string
*/
function remove_url_query($url, $key) {
$url = preg_replace('/(?:&|(\?))' . $key . '=[^&]*(?(1)&|)?/i', "$1", $url);
$url = rtrim($url, '?');
$url = rtrim($url, '&');
return $url;
}
Returns:
remove_url_query('http://example.com?a', 'a') => http://example.com
remove_url_query('http://example.com?a=1', 'a') => http:/example.com
remove_url_query('http://example.com?a=1&b=2', 'a') => http://example.com?b=2
Kudos to David Walsh.

Another solution, to avoid & problems too!!!
remove_query('http://example.com/?a=valueWith**&**inside&b=value');
Code:
function remove_query($url, $which_argument=false){
return preg_replace('/'. ($which_argument ? '(\&|)'.$which_argument.'(\=(.*?)((?=&(?!amp\;))|$)|(.*?)\b)' : '(\?.*)').'/i' , '', $url);
}

It wouldn't work if edit=1 is the first variable:
listitems.php?edit=1&color=green&...
You can use the $_GET variable to create the query string yourself. Something like:
$qs = '';
foreach ($_GET as $key => $value){
if ($key == 'pagenum'){
// Replace page number
$qs .= $key . '=' . $new_page_num . '&';
}elseif ($key != 'edit'){
// Keep all key/values, except 'edit'
$qs .= $key . '=' . urlencode($value) . '&';
}
}

Related

Remove one querystring parameter from a URL with multiple querystring parameters

I would like to remove a querystring parameter from a url that may contain multiple. I have succeeded in doing this using str_replace so far like this:
$area_querystring = urlencode($_GET['area']);
str_replace('area=' . $area_querystring, '', $url);
preg_replace also works, like this:
preg_replace('~(\?|&)area=[^&]*~', '$1', $url)
Either works fine for most URLs. For example:
http://localhost:8000/country/tw/?area=Taipei%2C+Taiwan&fruit=bananas
Becomes:
http://localhost:8000/country/tw/?&fruit=bananas
However, if the querystring contains an apostrophe html entity, nothing happens at all. E.g.:
http://localhost:8000/country/cn/?area=Shanghai%2C+People%27s+Republic+of+China&fruit=bananas
The %27 part of the url (an apostrophe) seems to be the cause.
To be clear, I don't wish to remove all of the URL after the last /, just the area querystring portion (the fruit=bananas part of the url should remain). Also, the area parameter does not always appear in the same place in the URL, sometimes it may appear after other querystring parameters e.g.
http://localhost:8000/country/tw/?lang=taiwanese&area=Taipei%2C+Taiwan&fruit=bananas
You can use the GET array and filter out the area key. Then rebuild the url with http_build_query. Like this:
$url = 'http://localhost:8000/country/cn/?area=Shanghai%2C+People%27s+Republic+of+China&fruit=bananas';
$filtered = array_filter($_GET, function ($key) {
return $key !== 'area';
}, ARRAY_FILTER_USE_KEY);
$parsed = parse_url($url);
$query = http_build_query($filtered);
$result = $parsed['scheme'] . "://" . $parsed['host'] . $parsed['path'] . "?" . $query;
You probably don't need urlencode() -- I'm guessing your $url variable is not yet encoded, so if there are any characters like an apostrophe, there won't be a match.
So:
$area_querystring = $_GET['area'];
should do the trick! No URL encoding/decoding needed.

How to keep specific URL parameters on links?

I have the following URL:
http://website.com/?utm_source=1&utm_campaign=2&utm_medium=3
When a user access my website with these parameters, all links on my pages get the parameters and merge with their original URL.
So if a link is:
http://website.com/link.html
It will become:
http://website.com/link.html?utm_source=1&utm_campaign=2&utm_medium=3
But my Google Analytics is going nuts with so much data. And I only need to keep utm_campaign.
Is that possible to get only the value of utm_campaign and apply on my URL even if I have others parameters?
Here is my current code:
if (isset($_REQUEST['utm_campaign']) {
$queryURL = "?" . preg_replace("/(s=[a-zA-Z%+0-9]*&)(.*)/", "$2", $_SERVER['QUERY_STRING'], -1);
$queryURL = preg_replace("/q=([a-z0-9A-Z-\/])+&(.*)/", "$2", $queryURL, -1);
$GLOBALS["queryURL"] = $queryURL;
} else {
$GLOBALS["queryURL"] = 0;
}
Work with the $_GET array rather than the query string:
if (isset($_REQUEST['utm_campaign'])) {
$query_string = '?utm_campaign=' . $_REQUEST['utm_campaign'];
} else {
$query_string = '';
}
Then when you create other links, you concatenate $query_string to them.
Yes, that is possible:
if (isset($_GET['utm_campaign'])) {
$newUrl = $oldUrl.(strpos($oldUrl,'?') ? '&' : '?').'utm_campaign='.$_GET['utm_campaign'];
}
This piece of code will change the old url to a new url. It takes any parameters of the old url into account. I use $_GET because you don't need $_POST which is also in $_REQUEST.

parse non encoded url

there is an external page, that passes a URL using a param value, in the querystring. to my page.
eg: page.php?URL=http://www.domain2.com?foo=bar
i tried saving the param using
$url = $_GET['url']
the problem is the reffering page does not send it encoded. and therefore it recognizes anything trailing the "&" as the beginning of a new param.
i need a way to parse the url in a way that anything trailing the second "?" is part or the passed url and not the acctual querystring.
Get the full querystring and then take out the 'URL=' part of it
$name = http_build_query($_GET);
$name = substr($name, strlen('URL='));
Antonio's answer is probably best. A less elegant way would also work:
$url = $_GET['url'];
$keys = array_keys($_GET);
$i=1;
foreach($_GET as $value) {
$url .= '&'.$keys[$i].'='.$value;
$i++;
}
echo $url;
Something like this might help:
// The full request
$request_full = $_SERVER["REQUEST_URI"];
// Position of the first "?" inside $request_full
$pos_question_mark = strpos($request_full, '?');
// Position of the query itself
$pos_query = $pos_question_mark + 1;
// Extract the malformed query from $request_full
$request_query = substr($request_full, $pos_query);
// Look for patterns that might corrupt the query
if (preg_match('/([^=]+[=])([^\&]+)([\&]+.+)?/', $request_query, $matches)) {
// If a match is found...
if (isset($_GET[$matches[1]])) {
// ... get rid of the original match...
unset($_GET[$matches[1]]);
// ... and replace it with a URL encoded version.
$_GET[$matches[1]] = urlencode($matches[2]);
}
}
As you have hinted in your question, the encoding of the URL you get is not as you want it: a & will mark a new argument for the current URL, not the one in the url parameter. If the URL were encoded correctly, the & would have been escaped as %26.
But, OK, given that you know for sure that everything following url= is not escaped and should be part of that parameter's value, you could do this:
$url = preg_replace("/^.*?([?&]url=(.*?))?$/i", "$2", $_SERVER["REQUEST_URI"]);
So if for example the current URL is:
http://www.myhost.com/page.php?a=1&URL=http://www.domain2.com?foo=bar&test=12
Then the returned value is:
http://www.domain2.com?foo=bar&test=12
See it running on eval.in.

Parsing closed brackets in URL and http_build_query with it inserts number in closed bracket

may not have explained this properly but here we go.
I have a URL that looks like http://www.test.co.uk/?page=2&area[]=thing&area[]=thing2
Multiple "area"s can be added or removed from the URL via links on the site. on each addition of n "area" I wanted to remove the "page" part of the URL. so it can be reset to page1. I used parse_url to take that bit out.
Then I built an http query so it could generate the URL properly without "page"
this resulted in "area%5B0%5D=" "area%5B1%5D=" instead of "area[]="
When I use urldecode, now it shows "area[0]=" and "area[1]="
I need it to be "[]" because when using a link to remove an area, it checks for the "[]=" - when it's [0] it doesn't recognise it. How do I keep it as "[]="?
See code below.
$currentURL = currentURL();
$parts = parse_url($currentURL);
parse_str($parts['query'], $query);
unset($query['page']);
$currenturlfinal = http_build_query($query);
urldecode($currenturlfinal);
$currentURL = "?" . urldecode($currenturlfinal);
This is what I've done so far - it fixes the visual part in the URL - however I don't think I've solved anything as I've realised that what represents 'area' and 'thing' is not recognised as $key or $val as a result of what I think is parsing or reencoding the url in accordance with the code below. So I still can't remove 'areas' using the links
$currentURL_with_QS2 = currentURL();
$parts = parse_url($currentURL_with_QS2);
parse_str($parts['query'], $query);
unset($query['page']);
$currenturlfinal = http_build_query($query);
$currenturlfinal = preg_replace('/%5B[0-9]+%5D/simU', '[]', $currenturlfinal);
urldecode($currenturlfinal);
$currentURL_with_QS = "?" . $currenturlfinal;
$numQueries = count(explode('&', $_SERVER['QUERY_STRING']));
$get = $_GET;
if (activeCat($val)) { // if this category is already set
$searchString = $key . '[]= ' . $val; // we build the query string to remove
I'm using Wordpress as well may I add - maybe there's a way to reset the pagination through Wordpress. of course even then - when I go to page 2 on any page it still changes the "[]" to "5b0%5d" etc....
EDIT: this is all part of a function that refers to $key (the area/category) and $val (name of area or category) which is echoed in the link itself
EDIT2: It works now!
I don't know why but I had to use the original code and make the adjustments I did before again and now it works exactly how I want it to! Yet I couldn't see any visible differences in both codes afterwards. Strange...
As far as I know, there is no built-in way to do this.
You could try with:
$currenturlfinal = http_build_query($query);
Where $query is querystring part w/o area parameters and then:
foreach ($areas as $area) {
$currenturlfinal .= '&area[]='.$area;
}
UPD:
you could try with:
$query = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query);
just place it right after http_build_query call.

php get all url variables

I'm trying to make links to include the current _GET variables.
Example link: Page 2
The current url is: http://example.com/test.php?id=2&a=1
So if someone clicks on the link of page 2 it will take them to:
http://example.com/test.php?id=2&a=1&page=2
Currently if they click on the link it takes them to:
http://example.com/test.php?page=2
As you can see, I need a way to get the current _GET variables in the url and add them to the link. Advice?
The superglobal entry $_SERVER['QUERY_STRING'] has the query string in it. You could just append that to any further links.
update: The alternate response on this page using http_build_query is better because it lets you add new variables to the query string without worrying about extraneous ?s and such. But I'll leave this here because I wanted to mention that you can access the literal query string that's in the current address.
$new_query_string = http_build_query(array_merge($_GET,array('page' => 2)));
Make use of #extract($_GET). So you can access them directly as variables.
Try this may help you......
function get_all_get()
{
$output = "?";
$firstRun = true;
foreach($_GET as $key=>$val) {
if($key != $parameter) {
if(!$firstRun) {
$output .= "&";
} else {
$firstRun = false;
}
$output .= $key."=".$val;
}
}
return $output;
}
As for the question above how to include the name of php file as well in the url, using Your Common Sense's perfect method and adding a question mark worked for me:
echo "<a href='?".$url."'>link</a>"

Categories