SERVER_NAME is not automatically told to reflect the actual domain name and path. This is defined in the VirtualHost configuration file usually in apache/conf/extra. You'll need to parse the HTTP_HOST in combination with the SERVER_PROTOCOL and SERVER_PORT to get the real domain name.
$domain = $_SERVER['HTTP_HOST'];
$protocol = (strpos('https', strtolower($_SERVER['SERVER_PROTOCOL'])))
? 'https'
: 'http';
$port = ($_SERVER['SERVER_PORT'] != 80 || $_SERVER['SERVER_PORT'] != 443 && $protocol != "https")
? ":".$_SERVER['SERVER_PORT']
: "";
$path = sub_str(str_pos("index.php", $_SERVER['PHP_SELF']), -1, $_SERVER['PHP_SELF']);
$done = $protocol . "://".$domain.$protocol.$path;
Code not tested but should show you the flow.
Edit: As for your path name you should parse the PHP_SELF variable, and remove everything starting from index.php (or your script file name).