我如何在PHP中获得当前包含脚本的url


How do I get the url of the current include script in 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")到文件)中使用的URL。

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

我该怎么做?

使用$_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'] ), '/' );

这是我使用了很长时间的一个简洁的行,它工作得很好。

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

EDIT使用我从PHP手册中提取的这个函数的编辑版本和__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;

获取文件的浏览器路径(我将其包含在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'];