php get all url variables - php

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>"

Related

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.

php; remove single variable value pair from querystring

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) . '&';
}
}

Add/Replace URL GET parameter depending on current URL

I’ve tried for some time now to solve what probably is a small issue but I just can’t seem get my head around it. I’ve tried some different approaches, some found at SO but none has worked yet.
The problem consists of this:
I’ve a show-room page where I show some cloth. On each single item of cloth there is four “views”
Male
Female
Front
Back
Now, the users can filter this by either viewing the male or female model but they can also filter by viewing front or back of both gender.
I’ve created my script so it detects the URL query and display the correct data but my problem is to “build” the URL correctly.
When firstly enter the page, the four links is like this:
example.com?gender=male
example.com?gender=female
example.com?site=front
example.com?site=back
This work because it’s the “default” view (the default view is set to gender=male && site=front) in the model.
But if I choose to view ?gender=female the users should be able to filter it once more by adding &site=back so the complete URL would be: example.com?gender=female&site=back
And if I then press the link to see gender=male it should still keep the URL parameter &site=back.
What I’ve achived so far is to append the parameters to the existing URL but this result in URL strings like: example.com?gender=male&site=front&gender=female and so on…
I’ve tried but to use the parse_url function, the http_build_query($parms) method and to make my “own” function that checks for existing parameters but it does not work.
My latest try was this:
_setURL(‘http://example.com?gender=male’, ‘site’, ‘back’);
function _setURL($url, $key, $value) {
$separator = (parse_url($url, PHP_URL_QUERY) == NULL) ? '?' : '&';
$query = $key."=".$value;
$url .= $separator . $query;
var_dump($url); exit;
}
This function works unless the $_GET parameter already exists and thus should be replaced and not added.
I’m not sure if there is some “best practice” to solve this and as I said I’ve looked at a lot of answers on SO but none which was spot on my issue.
I hope I’ve explained myself otherwise please let me know and I’ll elaborate.
Any help or advice would be appreciated
You can generate the links dynamically using the following method:
$frontLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=front':'mydomain.com?site=front';
$backLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=back':'mydomain.com?site=back';
This is a 1 line if statement which will set the value of the variables $frontLink and $backlink respectively. The syntax for a 1 line if statement is $var = (if_statement) ? true_result:false_result; this will set the value of $var to the true_result or false_result depending on the return value of the if statement.
You can then do the same for the genders:
$maleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=male&site='.$_GET['site']:'mydomain.com?gender=male';
$femaleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=female&site='.$_GET['site']:'mydomain.com?gender=female';
Found this by searching for a better solution then mine and found this ugly one (That we see a lot on the web), so here is my solution :
function add_get_parameter($arg, $value)
{
$_GET[$arg] = $value;
return "?" . http_build_query($_GET);
}
<?php
function requestUriAddGetParams(array $params)
{
$parseRes=parse_url($_REQUEST['REQUEST_URI']);
$params=array_merge($_GET, $params);
return $parseRes['path'].'?'.http_build_query($params);
}
?>
if(isset($_GET['diagid']) && $_GET['diagid']!='') {
$repParam = "&diagid=".$_GET['diagid'];
$params = str_replace($repParam, "", $_SERVER['REQUEST_URI']);
$url = "http://".$_SERVER['HTTP_HOST'].$params."&diagid=".$ID;
}
else $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."&diagid=".$ID;

Adding a query string to a random URL

I want to add a query string to a URL, however, the URL format is unpredictable. The URL can be
http://example.com/page/ -> http://example.com/page/?myquery=string
http://example.com/page -> http://example.com/page?myquery=string
http://example.com?p=page -> http://example.com?p=page&myquery=string
These are the URLs I'm thinking of, but it's possible that there are other formats that I'm not aware of.
I'm wondering if there is a standard, library or a common way to do this. I'm using PHP.
Edit: I'm using Cbroe explanation and Passerby code. There is another function by Hamza but I guess it'd be better to use PHP functions and also have cleaner/shorter code.
function addQuery($url,array $query)
{
$cache=parse_url($url,PHP_URL_QUERY);
if(empty($cache)) return $url."?".http_build_query($query);
else return $url."&".http_build_query($query);
}
// test
$test=array("http://example.com/page/","http://example.com/page","http://example.com/?p=page");
print_r(array_map(function($v){
return addQuery($v,array("myquery"=>"string"));
},$test));
Live demo
I'm wondering if there is a standard, library or a common way to do this. I'm using PHP.
Depends on how failsafe – and thereby more complex – you want it to be.
The simplest way would be to look for whether there’s a ? in the URL – if so, append &myquery=string, else append ?myquery=string. This should cover most cases of standards-compliant URLs just fine.
If you want it more complex, you could take the URL apart using parse_url and then parse_str, then add the key myquery with value string to the array the second function returns – and then put it all back together again, using http_build_query for the new query string part.
Some spaghetti Code:
echo addToUrl('http://example.com/page/','myquery', 'string').'<br>';
echo addToUrl('http://example.com/page','myquery', 'string').'<br>';
echo addToUrl('http://example.com/page/wut/?aaa=2','myquery', 'string').'<br>';
echo addToUrl('http://example.com?p=page','myquery', 'string');
function addToUrl($url, $var, $val){
$array = parse_url($url);
if(isset($array['query'])){
parse_str($array['query'], $values);
}
$values[$var] = $val;
unset($array['query']);
$options = '';$c = count($values) - 1;
$i=0;
foreach($values as $k => $v){
if($i == $c){
$options .= $k.'='.$v;
}else{
$options .= $k.'='.$v.'&';
}
$i++;
}
$return = $array['scheme'].'://'.$array['host'].(isset($array['path']) ? $array['path']: '') . '?' . $options;
return $return;
}
Results:
http://example.com/page/?myquery=string
http://example.com/page?myquery=string
http://example.com/page/wut/?aaa=2&myquery=string
http://example.com?p=page&myquery=string
You should try the http_build_query() function, I think that's what you're looking for, and maybe a bit of parse_str(), too.

Persistent HTTP GET variables in PHP

Let's say I have some code like this
if(isset($_GET['foo']))
//do something
if(isset($_GET['bar']))
//do something else
If a user is at example.com/?foo=abc and clicks on a link to set bar=xyz, I want to easily take them to example.com/?foo=abc&bar=xyz, rather than example.com/?bar=xyz.
I can think of a few very messy ways to do this, but I'm sure there's something cleaner that I don't know about and haven't been able to track down via Google.
Here's one way....
//get passed params
//(you might do some sanitizing at this point)
$params=$_GET;
//morph the params with new values
$params['bar']='xyz';
//build new query string
$query='';
$sep='?';
foreach($params as $name=>$value)
{
$query.=$sep.$name.'='.urlencode($value);
$sep='&';
}
If you are updating the query string you need ot make sure you don't do something like
$qs="a=1&b=2";
$href="$qs&b=4";
$href contains "a=1&b=2&b=4"
What you really want to do is overwrite the current key if you need to .
You can use a function like this. (disclaimer: Off the top of my head, maybe slightly bugged)
function getUpdateQS($key,$value)
{
foreach ($_GET as $k => $v)
{
if ($k != $key)
{
$qs .= "$k=".urlencode($v)."&"
}
else
{
$qs .= "$key=".urlencode($value)."&";
}
}
return $qs
}
View report
Just set the link that changes bar to xyz to also have foo=abc if foo is already set.
$link = ($_GET['foo'] == 'abc') ? 'foo=abc&bar=xyz' : 'bar=xyz';
?>
Click Me
You would have to render out the links with the proper URL querystring to make that happen. This is a design decision that you would need to make on your end depending on how your system is setup.
I have some sites that have this issue, and what I do is setup a querystring global variable that sets the current page data the top of the page request.
Then when I am rendering the page, if I need to make use of the current query string I do something like:
echo '<a href="myurl.php' . querystring . '&bar=foo';
It's not the cleanest, but it all depends on how your system works.
Save some code and use the built-in http_build_query. I use this wrapper in one of my projects:
function to_query_string($array) {
if(is_scalar($array)) $query = trim($array, '? \t\n\r\0\x0B'); // I could split on "&" and "=" do some urlencode-ing here
else $query = http_build_query($array);
return '?'.$query;
}
Also, though it isn't often used, you can have $_GET on the left-hand side of an assignment:
$_GET['overriden_or_new'] = 'new_value';
echo 'Yeah!';
Other than that, just do what Paul Dixon said.

Categories