php add GET at last string - php

i want to add utm_source=twitter in the of the links
i have a link let say
http://abcd.com/news?id=1
it need to be http://abcd.com/news?id=1&utm_source=twitter
if http://abcd.com/news/1
it need to be
http://abcd.com/news/1?utm_source=twitter
any idea?

To check if your link already has URL parameters on the end of it, look for the ? character in the URL. If it's there, use a & instead.
$link = 'http://abcd.com/news?id=1'; // or http://abcd.com/news
$join_char = strpos($string, '?') !== -1 ? '&' : '?'; // determine if we need & or ?
$link .= $join_char . 'utm_source=twitter';

You can check if the URL already contains a query string and branch your logic accordingly:
if (strpos($url, '?') === FALSE) {
$url .= '?utm_source=twitter';
} else {
$url .= '&utm_source=twitter';
}

If you're simply adding it to the end of a link it would look something like
$link . "?utm_source=twitter";

Related

Remove subdomain from URL/host to match domains in affiliate link array

I want to make a redirect file using php which can add Affiliates tag automatically to all links. Like how it works https://freekaamaal.com/links?url=https://www.amazon.in/ .
If I open the above link it automatically add affiliate tag to the link and the final link which is open is this ‘https://www.amazon.in/?tag=freekaamaal-21‘ And same for Flipkart and many other sites also.
It automatically add affiliate tags to various links. For example amazon, Flipkart, ajio,etc.
I’ll be very thankful if anyone can help me regarding this.
Thanks in advance 🙏
Right now i made this below code but problem is that sometimes link have extra subdomain for example https://dl.flipkart.com/ or https://m.shopclues.com/ , etc for these type links it does not redirect from the array instead of this it redirect to default link.
<?php
$subid = isset($_GET['subid']) ? $_GET['subid'] : 'telegram'; //subid for external tracking
$affid = $_GET['url']; //main link
$parse = parse_url($affid);
$host = $parse['host'];
$host = str_ireplace('www.', '', $host);
//flipkart affiliate link generates here
$url_parts = parse_url($affid);
$url_parts['host'] = 'dl.flipkart.com';
$url_parts['path'] .= "/";
if(strpos($url_parts['path'],"/dl/") !== 0) $url_parts['path'] = '/dl'.rtrim($url_parts['path'],"/");
$url = $url_parts['scheme'] . "://" . $url_parts['host'] . $url_parts['path'] . (empty($url_parts['query']) ? '' : '?' . $url_parts['query']);
$afftag = "harshk&affExtParam1=$subid"; //our affiliate ID
if (strpos($url, '?') !== false) {
if (substr($url, -1) == "&") {
$url = $url.'affid='.$afftag;
} else {
$url = $url.'&affid='.$afftag;
}
} else { // start a new query string
$url = $url.'?affid='.$afftag;
}
$flipkartlink = $url;
//amazon link generates here
$amazon = $affid;
$amzntag = "subhdeals-21"; //our affiliate ID
if (strpos($amazon, '?') !== false) {
if (substr($amazon, -1) == "&") {
$amazon = $amazon.'tag='.$amzntag;
} else {
$amazon = $amazon.'&tag='.$amzntag;
}
} else { // start a new query string
$amazon = $amazon.'?tag='.$amzntag;
}
}
$amazonlink = $amazon;
$cueurl = "https://linksredirect.com/?subid=$subid&source=linkkit&url="; //cuelinks deeplink for redirection
$ulpsub = '&subid=' .$subid; //subid
$encoded = urlencode($affid); //url encode
$home = $cueurl . $encoded; // default link for redirection.
$partner = array( //Insert links here
"amazon.in" => "$amazonlink",
"flipkart.com" => "$flipkartlink",
"shopclues.com" => $cueurl . $encoded,
"aliexpress.com" => $cueurl . $encoded,
"ajio.com" => "https://ad.admitad.com/g/?ulp=$encoded$ulpsub",
"croma.com" => "https://ad.admitad.com/g/?ulp=$encoded$ulpsub",
"myntra.com" => "https://ad.admitad.com/g/?ulp=$encoded$ulpsub",
);
$store = array_key_exists($host, $partner) === false ? $home : $partner[$host]; //Checks if the host exists if not then redirect to your default link
header("Location: $store"); //Do not changing
exit(); //Do not changing
?>
Thank you for updating your answer with the code you have and explaining what the actual problem is. Since your reference array for the affiliate links is indexed by base domain, we will need to normalize the hostname to remove any possible subdomains. Right now you have:
$host = str_ireplace('www.', '', $host);
Which will do the job only if the subdomain is www., obviously. Now, one might be tempted to simply explode by . and take the last two components. However that'd fail with your .co.id and other second-level domains. We're better off using a regular expression.
One could craft a universal regular expression that handles all possible second-level domains (co., net., org.; edu.,...) but that'd become a long list. For your use case, since your list currently only has the .com, .in and .co.in domain extensions, and is unlikely to have many more, we'll just hard-code these into the regex to keep things fast and simple:
$host = preg_replace('#^.*?([^.]+\.)(com|id|co\.id)$#i', '\1\2', $host);
To explain the regex we're using:
^ start-of-subject anchor;
.*? ungreedy optional match for any characters (if a subdomain -- or a sub-sub-domain exists);
([^.]+\.) capturing group for non-. characters followed by . (main domain name)
(com|id|co\.id) capturing group for domain extension (add to list as necessary)
$ end-of-subject anchor
Then we replace the hostname with the contents of the capture groups that matched domain. and its extension. This will return example.com for www.example.com, foo.bar.example.com -- or example.com; and example.co.id for www.example.co.id, foo.bar.example.co.id -- or example.co.id. This should help your script work as intended. If there are further problems, please update the OP and we'll see what solutions are available.

Detecting if a URL contains a certain string but NOT as a parameter using PHP

I'm trying to force different modes of debugging based on different development urls using PHP. I currently have this set up:
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']), 'https') === FALSE ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];
$req_uri = $_SERVER['REQUEST_URI'];
$currentUrl = $protocol . '://' . $host . $req_uri;
$hostArray = array("localhost", "host.integration", "10.105.0"); //Don't use minification on these urls
for ($i = 0; $i < count($hostArray); $i++) {
if (strpos($currentUrl, $hostArray[$i])) {
$useMin = false;
}
}
However, using this method, you would be able to trigger the $useMin = false condition if you were to pass any of the strings in the host array as a parameter, for example:
http://domain.com?localhost
How do I write something that will prevent $useMin = false unless the URL starts with that condition (or is not contained anywhere after the ? in the url parameter)?
Don't use the $currentUrl when checking $hostArray, just check to see if the $host itself is in the $hostArray.
If you want to check for an exact match:
if(in_array($host, $hostArray)) {
$useMin = false;
}
Or maybe you want to do this, and check to see if an item in $hostArray exists anywhere within your $host:
foreach($hostArray AS $checkHost) {
if(strstr($host, $checkHost)) {
$useMin = false;
}
}
And if you only want to find a match if $host starts with an item in $hostArray:
foreach($hostArray AS $checkHost) {
if(strpos($host, $checkHost) === 0) {
$useMin = false;
}
}
I can't comment so I'll post here. Why do you check the host array with the url, why not check it directly with the host as in:
if (strpos($host, $hostArray[$i])) {

PHP URL Directory

If the URL is the following :
If: http://www.imvu-e.com/products/dnr/
Then: http://www.imvu-e.com/products/dnr/
If: http://www.imvu-e.com/products/dnr/?
Then: http://www.imvu-e.com/products/dnr/
If: http://www.imvu-e.com/products/dnr/index.php
Then: http://www.imvu-e.com/products/dnr/
If: http://www.imvu-e.com/products/dnr/page.php?var=2
Then: http://www.imvu-e.com/products/dnr/
If: http://www.imvu-e.com/products/dnr
Then: http://www.imvu-e.com/products/
How can I do this?
My attempt:
print "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI'])."/";
Have a look at parse_url() function.
It returns anything you need.
Simply print_r() the result from parse_url to see what you get back.
You probably want something like:
$ARRurlParts = parse_url($orgurl);
$newURL = $ARRelem["scheme"].
"://".$ARRelem["host"].
((isset($ARRelem["port"]))?":".$ARRelem["port"]:"").
$ARRelem["path"];
The issue with your "attempt" is that $_SERVER['REQUEST_URI'] will contain everything the user passed, including index.php and question mark and possibly more. In order to get what you are after, you need to parse the $_SERVER['REQUEST_URI']:
If it ends with a slash /, leave it as it it
Otherwise, find the last slash in the string and take the substring from the beginning up to and including this slash
Finally append the result onto the http:// (or https:// with the domain name)
Ended up going with this
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
$address = $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
$parseUrl = parse_url(trim($address));
$parent = (substr($parseUrl['path'], -1) == '/') ? $parseUrl['path'] : dirname($parseUrl['path']) . "/";
return $parseUrl['scheme'] . '://' . $parseUrl['host'] . $parseUrl['port'] . $parent;
Inspired in part by Erwin Moller's answer (Why I voted it) and snipplets across web.
You can strip everything from the last backslash till the end of the string. I am pretty sure that dirname($_SERVER['REQUEST_URI']) won't do the job. You can also try using dirname($_SERVER['SCRIPT_FILENAME']). The last shoud work if you don't have some fancy .htaccess rewrite rules.

How to retrieve complete URL from address bar using PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get full URL on the address bar using PHP
I use this function, but it does not work all the time. Can anyone give a hint?
function sofa_get_uri() {
$host = $_SERVER['SERVER_NAME'];
$self = $_SERVER["REQUEST_URI"];
$query = !empty($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : null;
$ref = !empty($query) ? "http://$host$self?$query" : "http://$host$self";
return $ref;
}
I want to retrieve the link in address bar (exactly) to use it to refer user back when he sign out. The urls are different:
http://domain.com/sample/address/?arg=bla
http://domain.com/?show=bla&act=bla&view=bla
http://domain.com/nice/permalinks/setup
But I can't get a function that works on all cases and give me the true referrer.
Hint please.
How about this?
function getAddress() {
$protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
return $protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
echo getAddress();
You could use functions above to retrieve URL till GET parameters.
So You have string like = 'localhost/site/tmp' (example).
After that you could just loop through GET parameters if can't get anything else to work.
Add '?' at the end of string manually.
$str = 'localhost/site/tmp/?'
foreach ($_GET as $key => $value) {
$str .= $key.'='.$value.'&';
}
substr_replace($str, "", -1);
echo $str;
At the end You are deleting last symbol which is '&' and is not needed.

Format a website´s URL as a string with http:// upfront

I have a comment system that allows auto linking of url. I am using cakephp but the solution is more just PHP. here is what is happening.
if the user enters fully qualified url with http:// or https:// everything is fine.
but if they enter www.scoobydoobydoo.com it turns into http://cool-domain.com/www.scoobydoobydoo.com. basically cakephp understands that http|https is an external url so it works with http|https not otherwise.
My idea was to do some kind of str stuff on the url and get it to insert the http if not present. unfortunately whatever i try only makes it worse. I am noob :) any help / pointer is appreciated.
thanks
EDIT: posting solution snippet. may not be the best but thanks to answer at least I have something.
<?php
$proto_scheme = parse_url($webAddress,PHP_URL_SCHEME);
if((!stristr($proto_scheme,'http')) || (!stristr($proto_scheme,'http'))){
$webAddress = 'http://'.$webAddress;
}
?>
$url = "blahblah.com";
// to clarify, this shouldn't be === false, but rather !== 0
if (0 !== strpos($url, 'http://') && 0 !== strpos($url, 'https://')) {
$url = "http://{$url}";
}
Try the parse_url function: http://php.net/manual/en/function.parse-url.php
I think this will help you.
I've had a similar issue, so I created the following php function:
function format_url($url)
{
if(!$url) return null;
$parsed_url = parse_url($url);
$schema = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : 'http://';
$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
return "$schema$host$path";
}
if you format the following: format_url('abcde.com'), the result will be http://abcde.com.
Here is the regex: https://stackoverflow.com/a/2762083/4374834
p.s. #Vangel, Michael McTiernan's answer is correct, so please, learn your PHP before you say, that something might fail :)

Categories