detect and replace affiliate ID from URLs - php

I was trying to detect affiliate ID from URLs for a website running in PHP.
the URL examples are
I have changed the affiliate ID into real ones.
https://flipkart.com/product-name/product-id?marketplace=FLIPKART&affid=honor&ppn=something
https://flipkart.com/product-name/product-id?marketplace=FLIPKART&affid=apple&ppn=something
https://flipkart.com/product-name/product-id?marketplace=FLIPKART&affid=sony&ppn=something
I want to replace it with affid=sthachilo
These URLs will be saved in database.
So I cant use $_GET["affid"]
when the URL is shown, I just want to replace the affiliate ID.
or I can use it to replace the affiliate ID and save it in the database.
But I dont know how to detect the affid= section and replace whatever is there.
I tried the following code, but it doesnt seems to be working
$url = "https://flipkart.com/product-name/product-id?marketplace=FLIPKART&affid=sony&ppn=something";
$newurl = preg_replace('/&affid=(\d+)/','&affid=sthachilo',$url);
echo $newurl;
Here is a real URL example with my affiliate ID in it.
https://www.flipkart.com/complan-kesar-badam/p/itmew2cdj5dmthjk?marketplace=FLIPKART&iid=e6c16ab0-c15d-49c2-843e-cf4a5104c53b.MDMETGN5YZZ5MRYG.SEARCH&ppt=browse&lid=LSTMDMETGN5YZZ5MRYGTBFFJO&srno=b_1_1&pid=MDMETGN5YZZ5MRYG&affid=sthachilo&ssid=7bwqga35j40000001588133282410&ppn=browse
atleast I want to remove everything after itmew2cdj5dmthjk
and add affiliate ID at the end.
for example
https://www.flipkart.com/complan-kesar-badam/p/itmew2cdj5dmthjk?affid=sthachilo
Thanks in advance

you can use parse_url to get the url parts and than use parse_str to get the url query
$url = "https://flipkart.com/product-name/product-id?marketplace=FLIPKART&affid=sony&ppn=something";
// parse url
$parse = parse_url($url);
// parse the query
parse_str($parse['query'], $query);
// replace the affid with your desired value
$query['affid'] = 'samsung';
// rebuild the query
$parse['query'] = http_build_query($query);
// rebuild the final url
$final_url = $parse['scheme'].'://'.$parse['host'].$parse['path'].'?'.$parse['query'];
echo $final_url
// output : https://flipkart.com/product-name/product-id?marketplace=FLIPKART&affid=samsung&ppn=something

To replace the given affiliate ID with android:
$url = "https://flipkart.com/product-name/product-id?marketplace=FLIPKART&affid=apple&ppn=something";
$newurl = preg_replace('/&affid=(.+)?&/','&affid=android&',$url);
Probably not the best way to do it since it assumes affid is surrounded by & but if you know that will always be the case then this will work.

Related

Making user pages using PHP and MYSQL by getting user_name from URL: user/username

I am using PHP header redirect to redirect users from account/?id=$id to user/$username
Successfully it takes for instance account/?id=1 to user/samuel as long as the user exists. Now, this page user/samuel is quite empty ( 404 ).
How do I make it return the user data in the user/samuel using something like isset($_GET[]) manual? in addition of course to adding MYSQL query to retrieve data for the user which has username extracted from the URL, and get their data from database table. and I will be placing all the code in user/index.php
As long as I could make account/?id=$id get the $id from URL ( parameter ) and do other db stuff I think it is also possible to get $username from the URL.. even though user/?username could do it but I don't want to include an ? in the URL..
Any thoughts?
This is a pretty broad topic, what you need to do is parse the url - IE break it into parts and then match the url to a set of actions. This is commonly known as routing.
A naive implementation would be a:
$parts = explode($_SERVER['REQUEST_URI'], '/');
if ( $parts[-2] === 'user' && $parts[-1] ) {
$stmt = $pdo->prepare("SELECT * FROM 'users' WHERE username = ? OR id = ?");
$result = $stmt->execute(array($parts[-1], array($parts[-1]));
// ... do something if the user is found or not.
}
But this would fail if the url contains query parameters (?foo=bar) or a hash (#foo).
Instead you can use parse_url to make sure you only use the path.
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$parts = null;
// Match the url with a regular expression.
preg_match(/^\/user\/(\w*)$/, $path, $parts);
if ( count($parts) == 2 ) {
$stmt = $pdo->prepare("SELECT * FROM 'users' WHERE username = ? OR id = ?");
$result = $stmt->execute(array($parts[-1], array($parts[-1]));
// ... do something if the user is found or not.
}
But in the end you might want consider using a micro framework such as Silex, Slim or using the Routing component from Symfony2 so that you can concentrate on building your application rather than reinventing the wheel.
It might be better if you use Url Rewriting (aka friendly urls)
You can see this link which answers this same question, although your case is a little bit different.
Apache friendly urls
Since you can't convert $id to $username (both are different values) I would recommend to change the link to 'user/ID' instead of 'user/USERNAME'.

How do I strip the url of a google news json feed link

How do I strip the url of a google news json feed link?
My link looks like this
http%253A%252F%252Fwww.boston.com%252Fbusiness%252Fnews%252F2014%252F12%252F04%252Fnasa-poised-usher-new-era-with-orion-launch%252FGOh9asOZiRJPHbNw60otUK%252Fstory.html
I have used the following code
strip_tags("".$row['url']."");
This does not do anything, I'm guessing this is possible and I am using the wrong php function.
You can use urldecode for this.
$url = "http%253A%252F%252Fwww.boston.com%252Fbusiness%252Fnews%252F2014%252F12%252F04%252Fnasa-poised-usher-new-era-with-orion-launch%252FGOh9asOZiRJPHbNw60otUK%252Fstory.html";
$url = urldecode(urldecode($url));
echo $url; // Will output: http://www.boston.com/business/news/2014/12/04/nasa-poised-usher-new-era-with-orion-launch/GOh9asOZiRJPHbNw60otUK/story.html

Reduce link (URL) size

Is it possible to reduce the size of a link (in text form) by PHP or JS?
E.g. I might have links like these:
http://www.example.com/index.html <- Redirects to the root
http://www.example.com/folder1/page.html?start=true <- Redirects to page.html
http://www.example.com/folder1/page.html?start=false <- Redirects to page.html?start=false
The purpose is to find out, if the link can be shortened and still point to the same location. In these examples the first two links can be reduces, because the first points to the root, and the second has parameters that can be omitted.
The third link is then the case, where the parameters can't be omitted, meaning that it can't be reduced further than to remove the http://.
So the above links would be reduced like this:
Before: http://www.example.com/index.html
After: www.example.com
Before: http://www.example.com/folder1/page.html?start=true
After: www.example.com/folder1/page.html
Before: http://www.example.com/folder1/page.html?start=false
After: www.example.com/folder1/page.html?start=false
Is this possible by PHP or JS?
Note:
www.example.com is not a domain I own or have access to besides through the URL. The links are potentially unknown, and I'm looking for something like an automatic link shortener that can work by getting the URL and nothing else.
Actually I was thinking of something like a linkchecker that could check if the link works before and after the automatic trim, and if it doesn't then the check will be done again at a less trimmed version of the link. But that seemed like overkill...
Since you want to do this automatically, and you don't know how the parameters change the behaviour, you will have to do this by trial and error: Try to remove parts from an URL, and see if the server responds with a different page.
In the simplest case this could work somehow like this:
<?php
$originalUrl = "http://stackoverflow.com/questions/14135342/reduce-link-url-size";
$originalContent = file_get_contents($originalUrl);
$trimmedUrl = $originalUrl;
while($trimmedUrl) {
$trialUrl = dirname($trimmedUrl);
$trialContent = file_get_contents($trialUrl);
if ($trialContent == $originalContent) {
$trimmedUrl = $trialUrl;
} else {
break;
}
}
echo "Shortest equivalent URL: " . $trimmedUrl;
// output: Shortest equivalent URL: http://stackoverflow.com/questions/14135342
?>
For your usage scenario, your code would be a bit more complicated, as you would have to test for each parameter in turn to see if it is necessary. For a starting point, see the parse_url() and parse_str() functions.
A word of caution: this code is very slow, as it will perform lots of queries to every URL you want to shorten. Also, it will likely fail to shorten many URLs because the server might include stuff like timestamps in the response. This makes the problem very hard, and that's the reason why companies like google have many engineers that think about stuff like this :).
Yea, that's possible:
JS:
var url = 'http://www.example.com/folder1/page.html?start=true';
url = url.replace('http://','').replace('?start=true','').replace('/index.html','');
php:
$url = 'http://www.example.com/folder1/page.html?start=true';
$url = str_replace(array('http://', '?start=true', '/index.html'), "", $url);
(Each item in the array() will be replaced with "")
Here is a JS for you.
function trimURL(url, trimToRoot, trimParam){
var myRegexp = /(http:\/\/|https:\/\/)(.*)/g;
var match = myRegexp.exec(url);
url = match[2];
//alert(url); // www.google.com
if(trimParam===true){
url = url.split('?')[0];
}
if(trimToRoot === true){
url = url.split('/')[0];
}
return url
}
alert(trimURL('https://www.google.com/one/two.php?f=1'));
alert(trimURL('https://www.google.com/one/two.php?f=1', true));
alert(trimURL('https://www.google.com/one/two.php?f=1', false, true));
Fiddle: http://jsfiddle.net/5aRpQ/

Extracting part of a domain name

I have a url, members.exampledomain.com, and I would like to display only exampledomain onto my page.
For example http://members.exampledomain.com's index page has something like
<img src="members/images/logoexampledomain.png" />
Try using:
print_r($_SERVER);
and see if there is something you like there :)
Else if it is allways the same url like that, you can use $pieces = explode('.', $url); and $pieces[1] will contain exampledomain
If that doesn't work for you I have used javascript before to retrieve information out of urls before on pages where php would not run. I believe I retrieved it using window.location and had a function figure out what characters to look at so it would know where to split the url or retrieve out the information you want.
If you wish to do this with the domain as suggested above, the following code should work for you.
$full_domain = 'members.example.com';
$parts = explode('.', $full_domain);
array_slice($parts, -2, 2);
$domain = implode('.', $parts);
echo $domain;
This is a basic string parser for the domain. Things get much more complex when you are using multiple domains on the same script (aka Virtual hosting), and those domains have varying extensions such as .com.au .
If you wish to get the 'member' portion of the domain, you can add the following code after the above code:
$member = rtrim(str_replace($domain, '', $full_domain), '.');
echo $member;

Form Fix in php

I have a website form that collects url of users to store in a database. They should not enter the http:// with their URL however many and the result is that when their url is displayed it looks like this
http;//http://www.foo.com I need the form to strip it or ignore it or what ever you think is the best way to handle it.
thanks
Use this on the url given by the user:
$url=str_replace("http://","",$_POST['url']);
//Where $_POST['url'] is the users input
This function takes an argument and replaces all occurrences of that argument within a string. More on this function here.
You should do two things!
1 - Clean up your database and replace all http://http//example.org entries so that your database is fine with your convention (http://example.org, protocol is included in URL).
// Something like this ...
UPDATE table SET field = REPLACE(field, 'HTTP://HTTP://', 'HTTP://');
2 - After a user submitted his URL, you should check for the string "http://".
$url = trim('http://example.org');
if (0 !== strpos($url, 'http://')) {
$url .= 'http://' . $url;
}

Categories