How to create a $_SERVER['HTTP_HOST'] Link

Discussion in 'PHP' started by brandama, Jun 6, 2012.

  1. #1
    (I am not a coder, I am trying to learn though. Very much a beginner.)


     <?php
    $server=$_SERVER['HTTP_HOST'];
    echo "<a href=$server>$server</a>"
    ?
    Code (markup):
    This code generates a link of basedomain.com/basedomain.com

    Can anybody tell me why its not working?
     
    Solved! View solution.
    brandama, Jun 6, 2012 IP
  2. #2
    Because you don't include the scheme name (e.g. http://, etc) it assumes the value is a filename and attempts to reference it in the current location where the script is running. For example, if you put this script in a folder named "/test", then it would generate a link of: basedomain.com/test/basedomain.com

    The solution is to specify the scheme:

    
    <?php
    $server = $_SERVER['HTTP_HOST'];
    echo "<a href='http://$server'>$server</a>"
    ?>
    
    Code (markup):
    If you don't need this value anywhere else then you don't need to store the value first:

    
    <?php
    echo "<a href=\"http://".$_SERVER['HTTP_HOST']."\">".$_SERVER['HTTP_HOST']."</a>\n";
    ?>
    
    Code (markup):
     
    DaySeven, Jun 6, 2012 IP
  3. brandama

    brandama Member

    Messages:
    131
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    35
    #3
    Thanks Dayseven! In hindsight it makes sense to me know why it wasn't working.
     
    brandama, Jun 6, 2012 IP