使用PHP获取脚本的绝对URL?

Rob*_*Rob 2 php

基本上,我希望我的脚本输出其绝对URL,但我不想将其静态编程到脚本中.例如,如果我当前的URL是http://example.com/script.php我希望能够将其存储为变量,或者回显它.即$url = http://example.com/script.php;

但是如果我将脚本移动到不同的服务器/域,我希望它自动调整到那个,即 $url = http://example2.com/newscript.php;

但我不知道该怎么做.有任何想法吗?

Ais*_*ina 6

$url = "http://" . $_SERVER['HTTP_HOST'] . '/script.php';
Run Code Online (Sandbox Code Playgroud)

如果协议有可能也会改变(即https代替http),请使用:

$url = ($_SERVER['HTTPS'] ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . '/script.php';
Run Code Online (Sandbox Code Playgroud)