Search code examples
javascriptphphtmlaffiliate

Redirect based on Domain at URL-Variable


I am currently working on a fresh link system for my affiliate sites. However, I am still relatively inexperienced in the PHP area, even though I have always managed it. The affiliate links have a different structure and I would like to create a URL by means of PHP, with which these are automatically provided with the structure. I can not describe it very well, but I still try it with an example:

User X enters the URL "example.net/ref.php?url=NORMAL_URL" and depending on the domain in the "NORMAL_URL" a structure is applied. For example, an "? Aff = XYZ" is added to the URL "example.net/ref.php?url=http://example.de/". If the URL "example.net/ref.php?url=http://example.nl/" is directed to "affiliate_network.de/encoded_url=http%3A%2F%2Fexample.nl%2F I hope you have It at least a very small bit understood.Thanks for any help!

For a better understanding:


Solution

  • Send the url into this function, it uses preg_match with a regex from here to extract the domain part.
    $matches will be an array with the domain in element 1 so you can find it with $matches[1]
    This function checks if the array is empty (no domain is found) and will return null in that case It then uses a switch to compare the matched domain to a list of domains you can specify, if none of the domains listed match then it will again return null

    Within each case I have simply put a return value, but you can be creative and do anything you wish in there to build the URL in the way your application requires.

    I'd suggest rather than putting the redirect inside this function, which would be semantically confusing when you come to maintain your application later. You should check the return value of the function, and if it is not null redirect to the return value. If it is null, then you can do something else (display error for example)

    function getReturnFromURL($url) {
        $matches = null;
        preg_match("/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n]+)/im", $url, $matches);
        if (empty($matches)) return null;
        switch ($matches[1]) {
            case "ebay.de":
                return "ebay-network.de/XXX?encoded_url=the_encoded_?-{$matches[1]}";
                break;
            case "amazon.de":
                return "amazon.de/XXX?encoded_url=the_encoded_?-{$matches[1]}?tag=XYZ";
                break;
            default:
                return null;
        }
    }