【问题标题】:Getting the same web and file paths from scripts in different locations从不同位置的脚本获取相同的 Web 和文件路径
【发布时间】:2019-11-30 23:10:59
【问题描述】:

假设我有这个目录结构:

myApp
|____files
|
|__myFolder
|      |___script1.php
|
|__script2.php
|___myClass.php

script1.phpscript2.php 是相同的,它们所做的只是实例化 myClass,将文件放入 files 文件夹,然后打印出指向该文件的 HTML 锚链接。

//script1.php and script2.php:

/*require myClass*/

$myClass = new myClass();
$myClass->copyFile();
$link = $myClass->retHref();
echo '<a href="'.$link.'">Click here</a>

目前我在 myClass.php 中这样做,以获取绝对路径和 href:

//myClass.php

class myClass{

    public function copyFile()
    {
        $absPath = dirname(__FILE__).'/files/file.txt';
        //code to copy the file
    }

    public function retHref()
    {
        return $_SERVER['HTTP_REFERER'].'/files/file.txt';
    }

}

这是解决这个问题的最佳方法,还是有更好的方法

a) 获取文件路径

b) 创建网页链接

从一个类内部,当我不知道实例化该类并调用其函数的脚本将位于何处时?

【问题讨论】:

  • $_SERVER['HTTP_REFERER'] 不可靠,但使用起来非常简单。不幸的是,客户端总是有可能没有设置Referer 标头。因此,如果结果不是很重要,并且您有时没有链接也不介意,那么这种方法很好。但在任何需要该链接可用且准确的情况下,我都会遵循 atymic 答案中的建议。

标签: php webserver relative-path absolute-path fileserver


【解决方案1】:

您可以使用__DIR__ 常量来生成文件目录的绝对路径。在创建href 链接方面,它有点复杂。我在下面的示例中使用了来自this answer 的代码:

class myClass
{

    const FILE_DIRECTORY_PATH = __DIR__.'/files/file.txt';

    public function copyFile()
    {
        $pathToFile = self::FILE_DIRECTORY_PATH;
        //code to copy the file
    }

    public function retHref()
    {
        return $this->urlOrigin($_SERVER).'/files/file.txt';
    }

    private function urlOrigin($s, $use_forwarded_host = false)
    {
        $ssl = (!empty($s['HTTPS']) && $s['HTTPS'] == 'on');
        $sp = strtolower($s['SERVER_PROTOCOL']);
        $protocol = substr($sp, 0, strpos($sp, '/')).(($ssl) ? 's' : '');
        $port = $s['SERVER_PORT'];
        $port = ((!$ssl && $port == '80') || ($ssl && $port == '443')) ? '' : ':'.$port;
        $host = ($use_forwarded_host && isset($s['HTTP_X_FORWARDED_HOST'])) ? $s['HTTP_X_FORWARDED_HOST'] : (isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : null);
        $host = isset($host) ? $host : $s['SERVER_NAME'].$port;
        return $protocol.'://'.$host;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    相关资源
    最近更新 更多