How do you change affiliate link based on IP address ?

11 replies
Hi, does anyone know if it is possible to switch links depending on the visitor's IP address...

e.g. if someone from the UK accessed my site, I want my affiliate links to send the visitor to the UK company

if someone from Canada visited my site, then the links would send them to the Canadian company...

etc..

Can this be done in PHP, if at all ?
#address #affiliate #based #change #link
  • Profile picture of the author Chucksta
    I've got the info on how this is done, I just need to put it all together. I'll detail here how to do it once I have it working.
    Signature

    Free to use web based tools for the Internet Marketer http://www.internetmarketier.com/

    Make sure you join the forum and contribute with feedback and ideas.

    {{ DiscussionBoard.errors[4174889].message }}
    • Profile picture of the author Chucksta
      I've got some problems with the code not showing properly, the dollar symbol will not display... I'll remove this text once I resolve this issue

      HERE IS HOW TO CHANGE LINKS, TEXT, OR ANYTHING, BASED ON THE VISITOR'S IP ADDRESS

      SOURCES
      IP address list - actually, IP numbers
      FREE IP to Country Database (IPV4 and IPV6)
      Acquiring user's/visitor's IP address
      Obtaining users IP's with PHP
      PHP: $_SERVER - Manual
      IP address To IP number formula
      IP Address to IP Number Formula | IP-to-Country.com
      How to convert IP address to country name - CodeProject

      FILES CREATED
      Note: PHP is used for coding. More than one file is created.
      Main file: countryfinder.php - this is included somewhere near the start of the web page's HTML text that will use this system. I place it between the body and table entries, e.g.

      Code:
      <body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
      
              <?php
              	include 'countryfinder.php';
              ?>
      
      <!-- Save for Web Slices (new main page.psd) -->
      <table id="Table_01" width="850" border="0" cellpadding="0" cellspacing="0">
      The other php file or files created are the ones that swap out the actual text or links based on where the visitor's IP address is from. These files can have any name. I usually name them based on the web page name, e.g. index1.php, index2.php, index-link1.php, index-link2.php, etc.
      Signature

      Free to use web based tools for the Internet Marketer http://www.internetmarketier.com/

      Make sure you join the forum and contribute with feedback and ideas.

      {{ DiscussionBoard.errors[4196606].message }}
      • Profile picture of the author Chucksta
        STEPS TAKEN TO CREATE THESE FILES

        Step 1) Get the list of IP addresses
        First of all we need to get the list of IP addresses. This can be downloaded from a number of locations. I download mine from here:

        FREE IP to Country Database (IPV4 and IPV6)

        I download the IPV4 (zip) version
        note: these are IP numbers, but don't worry, we deal with that later (code to convert visitor's IP address to an IP number).
        This file is updated every month, so I advise grabbing the new one as it comes out.

        Format of file's data:
        "16777216","16777471","apnic","1272931200","AU","A US","Australia"

        The fields that are of interest here, are the first 2 - "16777216","16777471", which is an IP range. "AU" and "AUS", which are country codes, and "Australia", which is the country's name.
        Actually, the following code only makes use of the IP range, and 2nd country code, but you are free to use them as you will


        Step 2) Put the list of IP addresses into a database
        The format of the file allows for the list to be placed into a MySQL database.
        I don't use a standard database, I just use the CSV list itself with all the comments removed. The comments are at the start of the file, and are all the lines starting with a # symbol.

        It would be a LOT easier to use a MySQL database, but I don't trust databases held on a website host's systems.

        At the moment I only check if the IP address is from the UK or not. This is done by first grabbing the visitor's IP address (the person visiting my site), then loading up all UK IP addresses from the list into an array, then grab the visitor's IP address, then search the array looking to see if the visitor's IP address is one of the UK addresses.

        YEP, it would be a LOT easier with a proper database
        Signature

        Free to use web based tools for the Internet Marketer http://www.internetmarketier.com/

        Make sure you join the forum and contribute with feedback and ideas.

        {{ DiscussionBoard.errors[4196633].message }}
        • Profile picture of the author Chucksta
          Step 3) Grab and store visitor's IP address

          This is the start of the countryfinder.php file

          PHP Code:
          // Get visitor's IP address
          visitorIPAddress _SERVER['REMOTE_ADDR']; 
          Note: the variable visitorIPAddress and _SERVER should have a $ symbol at the start
          Signature

          Free to use web based tools for the Internet Marketer http://www.internetmarketier.com/

          Make sure you join the forum and contribute with feedback and ideas.

          {{ DiscussionBoard.errors[4196667].message }}
          • Profile picture of the author Chucksta
            Step 5) Next, we need to convert the visitor's IP address into an IP number, so that we can compare it with the IP number range in the IP number list

            PHP Code:
            // Convert visitor's IP address into an IP number
            // split IP address into its 4 parts
            visitorIP split(".","visitorIPAddress");
            // formula for converting IP address into an IP number
            ipNumber visitorIP[3] + visitorIP[2] * 256 visitorIP[1] * 65536 visitorIP[0] * 16777216

            Step 6) Next, Find visitor's country
            Remember, this example only checks to see if the visitor has a UK IP address
            Also note, The IP numbers in the file are held in ranges, beginning # to end #. Individual IP numbers are not held. Therefore we need to check if the visitor's IP number lies within the range of numbers in the list.
            Database peeps (MySql etc.) ignore this. You now need to search the database to see if the visitor's IP number is there, and to then set a flag stating the outcome (found or not)

            PHP Code:
            // Find visitor's country
            arraySize count(UKcountryCodesArray);
            // flag showing if the visitor is from the UK
            visitorIsFromTheUK "false";
            for (
            i=0arraySizei++)
            {
                
            // does the visitor's IP number lie within the current range ?
                
            if (ipNumber >= UKcountryCodesArray[i][0] && ipNumber <= UKcountryCodesArray[i][1])
                {
                    
            // YES it does
                    
            visitorIsFromTheUK "true";
                    
            arraySize;  // terminate the loop, as we no longer need to perform anymore checks
                
            }
            }
            ?> 
            That's the end of the countryfinder.php file
            Signature

            Free to use web based tools for the Internet Marketer http://www.internetmarketier.com/

            Make sure you join the forum and contribute with feedback and ideas.

            {{ DiscussionBoard.errors[4196728].message }}
            • Profile picture of the author Chucksta
              Step 7) Next, the code needed to switch links, text, or whatever, based on the visitor's IP address

              This I place in a separate php file to the above code, then include it in the html file where it will be needed, e.g. swapping the text "colour" or "color".

              Index1.php

              PHP Code:
              <?php
              // ==============================
              //  display the appropriate link
              // ==============================

                  
              if (visitorIsFromTheUK == "true")
                  echo 
              '<a href="http://www.amazon.co.uk/product/UKmembercodeblahblah">Cheap Video Games</a>';
              else
                  echo 
              '<a href="http://www.amazon.com/product/USmembercodeblahblah">Cheap Video Games</a>';
              ?>

              Step 8) Next, include this code in your HTML file. e.g. if you have a website for Cheap Video Games, and the index page has a heading of Cheap Video Games, you could include the index1.php file thus:

              BEFORE include used
              HTML Code:
              <h1>Cheap Video Games</h1>
              AFTER include used
              PHP Code:
              <h1>
              <?php
                  
              include 'index1.php';
              ?>
              </h1>
              Example 2: swapping text, British English and American English

              index2.php

              PHP Code:
              <?php
              // ==============================
              //  display colours or colors
              // ==============================
              if (visitorIsFromTheUK == "true")
                  echo 
              'colours';
              else
                  echo 
              'colors';
              ?>
              BEFORE include used
              HTML Code:
              <p>there are many colours to choose from</p>
              AFTER include used
              PHP Code:
              <p>
              <?php
                  
              include 'index2.php';
              ?>
              </p>
              Signature

              Free to use web based tools for the Internet Marketer http://www.internetmarketier.com/

              Make sure you join the forum and contribute with feedback and ideas.

              {{ DiscussionBoard.errors[4196739].message }}
              • Profile picture of the author Chucksta
                Finally, this is not perfect, but it works extremely well. People are not always using an IP address that identifies their actual country, and some people use anonymous browsing, thus hiding their true location. But most people use the net without trying to hide, so this will work fine for most of them.

                IMPROVEMENTS TO CODE: Any ideas on how to improve this, then please shout. I know I can improve the performance as far as loading the list into an array is concerned. Perhaps load a line, then check if visitor's address is in that range, then terminate loading/checking once the address is found...

                Hmm, something strange is happening to my code listings... variables are vanishing ?!?!?

                Also, I missed out step 3 ! Instead I have 2 step 4s !!!
                Signature

                Free to use web based tools for the Internet Marketer http://www.internetmarketier.com/

                Make sure you join the forum and contribute with feedback and ideas.

                {{ DiscussionBoard.errors[4196752].message }}
  • Profile picture of the author Chucksta
    Step 4) Next store the UK addresses into an array - $UkcountryCodesArray
    Databse peeps (MySql etc.) Those using a proper database that allows querying can ignore this

    PHP Code:
    // open IP address database    
    file fopen("countrycodes","r");    
    // store all lines of database in an array
    countLinesInUKArray 0;  // set to 1 to represent the 1st line of the file
    while (!feof(file))
    {
        
    // store current line from IP list file
        
    currentLine fgets(file);

        
    // split line into words
        
    wordsArray explode(",",currentLine);

        
    // remove quotes and store country code
        
    word str_replace(""","",wordsArray[5]);

        // store only UK addresses
        if (strcmp(word,'GBR')==0)
        { 
            // store separate words of line into current row of UK array
            for (i = 0; i < 7; i++)
            {
                UKcountryCodesArray[countLinesInUKArray][i] = str_replace("""
    ,"",wordsArray[i]);
            }
            
    // increment to next line
            
    countLinesInUKArray++;
        }
    }
    // close the current file
    fclose(file); 
    Signature

    Free to use web based tools for the Internet Marketer http://www.internetmarketier.com/

    Make sure you join the forum and contribute with feedback and ideas.

    {{ DiscussionBoard.errors[4196702].message }}
  • Profile picture of the author KirkMcD
    Well if you don't want to use a database, then you'll need to rethink the way you load the file, since that is the slowest part.

    Since you only care about certain countries, instead of reading the whole file and then only using parts of it, you should create a subset of the file with the countries you want to check for. It will only need to contain the ip range and the country code.
    Also if you are going to default to a certain country, you won't need to check for it either. So you can leave it out of your subset file too. The smaller the file is, the better your performance will be.

    Hmm, something strange is happening to my code listings... variables are vanishing ?!?!?
    Use Quote instead of Code
    {{ DiscussionBoard.errors[4196929].message }}
  • Profile picture of the author Chucksta
    Thanks, Kirk

    Some excellent tips there, and thanks for the quote tip, too.

    I'm still having problems replacing the first instance of step 4. Posting just keeps on hanging

    I'll persevere

    Edit: quote did not help, the problem with display of the code appears to be with the dollar symbol .... more research required to find out how to resolve this.
    Step 3 now posted where it should be, but without the dollar symbol at the start of the variable or _SERVER
    Signature

    Free to use web based tools for the Internet Marketer http://www.internetmarketier.com/

    Make sure you join the forum and contribute with feedback and ideas.

    {{ DiscussionBoard.errors[4197025].message }}
  • Profile picture of the author ChrisMoon
    Thanks Chucksta been looking for some way to switch links depending on IPs. I'm going to try this out and get back to you.

    regards,
    Chris Moon
    Signature

    GreyGable

    {{ DiscussionBoard.errors[4197061].message }}

Trending Topics