How to keep specific URL parameters on links? - php

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.

Related

How can I check the post slug?

Scenario: As you know, StackOverflow checks the title in the question. I mean when you open this URL:
http://stackoverflow.com/questions/38839016/should-i-store-the-result-of-an-function
automatically it will be replaced with this:
http://stackoverflow.com/questions/38839016/should-i-store-the-result-of-an-function-into-an-array
That replacement is because of being incomplete the first URL.
Ok well, I'm trying to make such a system by PHP. Here is my attempt:
// getting this from the URL
$id = '38839016';
// fetching this from database based on that id (38839016)
$real_title = $result['title'];
//=> Should I store the result of an function into an array
$real_title = str_replace("-"," ",strtolower($real_title));
//=> should-i-store-the-result-of-an-function-into-an-array
// getting whole uri
$current_uri = $_SERVER["REQUEST_URI"];
//=> /questions/38839016/should-i-store-the-result-of-an-function
What I want to do: I need to compare $real_title with title-part of the $current_uri. How can I determine "title-part"? It is everything which is after $id.'/' until / or ? or $ (end of string). How can I do that comparison?
And then:
if ( preg_match("//", $current_uri) ) {
// all fine. continue loading the page
continue;
} else {
// replace title-part of the $current_uri with $real_title
preg_replace("//", $real_title, $current_uri);
// redirect to this post with correct slug
header('Location: '.$_SERVER["HTTP_HOST"].);
}
briefly, I want to complete these:
if ( preg_match("//", $current_uri) ) {
preg_replace("//", $real_title, $current_uri);
Ok, in simple words, there is a good url and a requested url
if the requested url not equal the good url
redirect the visitor to the good one
<?
$id = '38839016';
$good_url = '/questions/'.$id.'/'.str_replace("-"," ",strtolower($result['title']));
preg_match( '/\/[0-9]+\/([a-z0-9-]+)\/.*/', $_SERVER[REQUEST_URI], $matches);
if ($matches[1] != str_replace("-"," ",strtolower($result['title'])))
header('Location: '.$good_url);

how to separate the request uri into a for loop to break down variables

i have the need to break down a REQUEST_URI to perform a few functions for each string between the slashes
the request that is passed from the url looks something like the below url however i cannot assign them static variables as the url could get longer or shorter per different pages
https://www.domain.com/accounts/customers/details
what im looking to do is capture the "accounts/customers/details" section which i have done by this variable on the page
$requested_url = $_SERVER['REQUEST_URI']; // this outputs /accounts/customers/details
i wish to create a for loop extracting the information from between the brackets and displaying it on page like
accounts
customers
details
how can this be achieved
try this
$requested_url = $_SERVER['REQUEST_URI'];
$seperate = explode("/",$requested_url); //this will explode in to array with "/" seperator
foreach($seperate as $seprt) {
echo $seprt."<br/>"; //it echo's each array variable seperately
}
$requested_url = $_SERVER['REQUEST_URI'];
$seperate = explode("/",$requested_url);
$count = 0;
foreach($seperate as $seprt) {
$count++;
if($count == count($seperate)){
echo $seprt;
}
}

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.

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

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