2

I am trying to create a link in a PHP script that will take me to the main part of my address (In bold): http://localhost:8888/index.php

I could put the exact link in myself but thought if I use the $_SERVER variable then it would allow for a degree for flexibility if I move the file etc.

I did a vardump($_SERVER) and it appears that $_SERVER['HTTP_ORIGIN'] contains the data that I require, however it also seems that this may not be an ideal variable to use: How secure is HTTP_ORIGIN?

Is this the correct way to create a dynamic link or is there an alternative?

Community
  • 1
  • 1
underflow
  • 483
  • 3
  • 15
  • If i'm not mistaken, it seems like [How secure HTTP_ORIGIN is?](http://stackoverflow.com/questions/4566378/how-secure-http-origin-is) is more about how secure `$_SERVER['HTTP_ORIGIN']` is concerning requests form 3rd party websites. You will probably be safe if you only want to create link. You should however use `SERVER_NAME` and `SERVER_PORT` as @ThiagoElias answered. – Chigurh Mar 14 '15 at 17:12
  • 1
    Why can you not just use a relative URI? `/`. – Quentin Mar 14 '15 at 17:14

2 Answers2

4

try to use

$address = 'http://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'];
Thiago Elias
  • 939
  • 1
  • 6
  • 21
3

To be extra flexible you could check if https or http is used and if a port other then default 80 or 443 (https) is used, also meaning if no port is defined in the URL.

function url(){
    $port = null;
    if( ($_SERVER['SERVER_PORT'] != '80') && ($_SERVER['SERVER_PORT'] != '443') ) {
        $port = ':' . $_SERVER['SERVER_PORT'];
    }

    $protocol = empty($_SERVER['HTTPS']) ? 'http://' : 'https://';

    return $protocol . $_SERVER['SERVER_NAME'] . $port;
}
Chigurh
  • 131
  • 1
  • 3
  • HTTPS use port 443 by default, not 80, so your function will add a port in the URL even if there wasn't in the original one if the user is on a HTTPS connection. – Benoit Esnard Mar 14 '15 at 18:50