I am trying to create a affiliate link geenrator using php and i am using the below code to generate. But this code add affid at last of link only when the link contains any affiliate tag. If i use this link then 'https://www.flipkart.com/whirlpool-1-5-ton-5-star-split-inverter-ac-white/p/itmf8fb8a675505d?pid=ACNFE6K2BXFY6EKX' it send me the same link without adding any tag.
Anyone can please help me reagarding this ?
$url = "https://www.flipkart.com/whirlpool-1-5-ton-5-star-split-inverter-ac-white/p/itmf8fb8a675505d?pid=ACNFE6K2BXFY6EKX";
$afftag = 'harshk'; //our affiliate ID
$affstring = 'affid='; // url parameter for affiliate ID
if (parse_url($url, PHP_URL_QUERY)): //check if link has query string
if (strpos($affstring, $url) !== true) : //check if link already has affiliate ID
$url = preg_replace("/(".$affstring.").*?(\z|&)/", "$1".$afftag."$2", $url);
else:
$url = $url.'&'.$affstring.$afftag;
endif;
else:
$url = $url.'?'.$affstring.$afftag;
endif;
Try if this works
$url = "https://www.flipkart.com/whirlpool-1-5-ton-5-star-split-inverter-ac-white/p/itmf8fb8a675505d?pid=ACNFE6K2BXFY6EKX";
$afftag = 'harshk'; //our affiliate ID
$affstring = 'affid='; // url parameter for affiliate ID
if (parse_url($url, PHP_URL_QUERY)): //check if link has query string
if (strpos($affstring, $url) === true) : //check if link already has affiliate ID
$url = preg_replace("/(" . $affstring . ").*?(\z|&)/", "$1" . $afftag . "$2", $url);
else:
$url = $url . '&' . $affstring . $afftag;
endif;
else:
$url = $url . '?' . $affstring . $afftag;
endif;
Solution#2
<?php
$urlStr = "https://www.flipkart.com/whirlpool-1-5-ton-5-star-split-inverter-ac-white/p/itmf8fb8a675505d?pid=ACNFE6K2BXFY6EKX";
$afftag = 'harshk'; //our affiliate ID
$affstring = 'affid'; // url parameter for affiliate ID
$url_components = parse_url($urlStr);
$params = [];
if (isset($url_components['query'])):
parse_str($url_components['query'], $params);
endif;
$url = "{$url_components['scheme']}://{$url_components['host']}{$url_components['path']}";
$params[$affstring] = $afftag;
$url .= "?" . http_build_query($params);