如何在PHP中获取当前包含脚本的URL?

时间:2011-09-05 14:48:02

标签: php

我有一个名为index.php的文件,其中包含来自另一个文件(class/event.class.php)的类,其中包含以下代码:

 <?php
      require_once('class/event.class.php');
      $evt = new Event;
      $evt->doSomething();
 ?>

文件event.class.php应该能够读取请求中使用的网址( $_SERVER["SCRIPT_FILENAME")到该文件。

ie:http://localhost:8888/class/event.class.php

我该怎么做?

3 个答案:

答案 0 :(得分:2)

使用$_SERVER数组,例如:

$protocol = 'http';
$port = '';

if ( isset( $_SERVER['HTTPS'] ) && strcasecmp( $_SERVER['HTTPS'], 'on' ) == 0 ) {
    $protocol = 'https';
}
if ( isset( $_SERVER['SERVER_PORT'] ) ) {
    $port = ':' . $_SERVER['SERVER_PORT'];
}

// Don't display the standard ports :80 for http and :443 for https
if ( ( $protocol == 'http' && $port == ':80' ) || ( $protocol == 'https' && $port == ':443' ) ) {
    $port = '';
}

$host_url = $protocol . '://' . $_SERVER['SERVER_NAME'] . $port;
$base_url = rtrim( str_replace( basename( $_SERVER['SCRIPT_NAME'] ), '', $_SERVER['SCRIPT_NAME'] ), '/' );

答案 1 :(得分:1)

这是我用了很长时间的简洁线条,它的效果非常好。

$myURL = ((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? 'https' : 'http').'://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

echo $myURL;

编辑使用此功能的编辑版本lifted from the PHP manual__FILE__魔术常量,可以这样做(未经测试):

function getRelativePath ( $path, $compareTo ) {

    // Replace \ with / and remove leading/trailing slashes (for Windows)
    $path = trim(str_replace('\\','/',$path),'/');
    $compareTo = trim(str_replace('\\','/',$compareTo),'/');

    // simple case: $compareTo is in $path
    if (strpos($path, $compareTo) === 0) {
        $offset = strlen($compareTo) + 1;
        return substr($path, $offset);
    }

    $relative  = array();
    $pathParts = explode('/', $path);
    $compareToParts = explode('/', $compareTo);

    foreach($compareToParts as $index => $part) {
        if (isset($pathParts[$index]) && $pathParts[$index] == $part) {
            continue;
        }
        $relative[] = '..';
    }

    foreach( $pathParts as $index => $part ) {
        if (isset($compareToParts[$index]) && $compareToParts[$index] == $part) {
            continue;
        }
        $relative[] = $part;
    }

    return implode('/',$relative);

}

$myURL = ((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? 'https' : 'http').'://'.$_SERVER['HTTP_HOST'].'/'.ltrim(getRelativePath(realpath($_SERVER['PHP_SELF']),__FILE__),'/');

echo $myURL;

答案 2 :(得分:1)

我做了什么来获取我的文件的浏览器路径(我在index.php中包含它,但在event.class.php中使用此代码将返回该文件夹):

$this_file = dirname($_SERVER['PHP_SELF']) . '/';

$a_file_that_you_want_to_access_by_url = $this_file.'class/event.class.php';

此外,如果要访问所有.php文件中的当前目录“root”,请定义如下常量:

define('uri_root',          dirname($_SERVER['PHP_SELF']) . '/',  true);
$a_file_that_you_want_to_access_by_url = uri_root.'class/event.class.php';

此脚本将使用所有子文件夹

回显脚本名称
echo dirname($_SERVER['PHP_SELF']).$_SERVER['PHP_SELF'];