Search code examples
phpgetdefault

How to pass multiple variables in a URL and have each one replaced by a default value if not supplied


In need of a little PHP help here.

The following PHP code works perfectly to pass an affiliate ID on a given website where the user adds their affiliate ID to the end of the URL, otherwise the default is used (I have been using this successfully).

Example:

www.example.com (uses 'defaultid' from the PHP code)

www.example.com/?id=test1 (uses the affiliate ID 'test1' supplied by the user)

<?php

/* DEFAULT SETTINGS */

$DEFAULT_ID = "defaultid";

/* Function to display ID value */

function displayID($defaultValue) {

global $_GET, $DEFAULT_ID;

if (isset($_GET['id']) and strlen(trim($_GET['id']))) {

 echo $_GET['id'];

} else if (strlen(trim($defaultValue))) {

 echo $defaultValue1;

} else {

 echo $DEFAULT_ID;

}

}

/* End of function to display ID value */

?>

What I'd like to know is how to modify above code to work for 3 different affiliate IDs where there are 3 hyperlinks on a given web page for 3 different affiliate offers.

Example:

www.example.com (uses 3 default IDs that I've defined in the code) www.example.com/?id1=test1 (uses default IDs 'defaultid2' and 'defaultid3') www.example.com/?id1=test1&id2=test2 (uses just the default ID 'defaultid3') www.example.com/?id1=test1&id2=test2&id3=test3 (uses the 3 IDs supplied in the URL by the affiliate)

Please note I am not PHP savvy, so a modification of the above code would be preferred (if possible), rather than a complete rewrite that I may not understand.


Solution

  • Well, to have a default value you can add this to your code:

    $id1="test1";
    $id2="test2";
    $id3="test3";
    
    if (isset($_GET['id1']) && strlen(trim($_GET['id1'])))
       $id1=$_GET['id1'];
    
    if (isset($_GET['id2']) && strlen(trim($_GET['id2'])))
       $id2=$_GET['id2'];
    
    if (isset($_GET['id3']) && strlen(trim($_GET['id3'])))
       $id3=$_GET['id3'];
    

    How this code works: You have three variables, one for each ID.

    The conditional will verify if there is anything in the $_GET array with the name for this id. If there is, it will overwrite the previous value, and if not, the default value will remain in there.

    Also, if you're a fan of ternary, this does the same and looks prettier:

    $id1= (isset($_GET['id1']) && strlen(trim($_GET['id1']))) ? $_GET['id1'] : "test1";
    $id2= (isset($_GET['id2']) && strlen(trim($_GET['id2']))) ? $_GET['id2'] : "test2";
    $id3= (isset($_GET['id3']) && strlen(trim($_GET['id3']))) ? $_GET['id3'] : "test3";