【问题标题】:PHP getcwd() function to be used with include or require in different directoriesPHP getcwd() 函数与不同目录中的 include 或 require 一起使用
【发布时间】:2012-04-27 16:49:42
【问题描述】:

我需要在其他脚本的一个目录中包含一个配置文件的路径,向上或向下几个目录。

我的配置文件有这样的功能:

$execute_path = getcwd() . "/execute.php";

execute.php 文件与配置文件位于同一目录中,这样就可以了,输出将变为:

public-html/config-directory/execute.php

现在,如果在原始目录之外的目录中使用相同的函数,它会将 getcwd() 函数视为在该目录中。

例如,如果从目录 public-html/one/two/three/somefile.php 调用它,如下所示:

<?php 
include(pathto/config.php)
echo $execute_path;
?>

输出变为 publichtml/one/two/three/execute.php 而不是保持 publichtml/config-directory/execute.php

我怎样才能在这里实现我想要的?抱歉,解释太长了。谢谢。

【问题讨论】:

    标签: php include-path getcwd


    【解决方案1】:

    包含可能非常棘手,为什么我的建议是

    //config.php
    
    define("SITE_PATH", "public-html/config-directory");
    
    
    //execute.php
    
    $execute_path =SITE_PATH . "/execute.php";
    
    //run.php
    include_once 'config.php';
    include_once 'execute.php';
    
    echo $execute_path;
    

    【讨论】:

    • 问题是配置文件是根据用户服务器设置生成的,以及他们上传主(它是一个插件)目录的位置。这意味着在配置文件中手动定义路径是行不通的。
    • 它更安全,因为它的配置和你不会一直在工作目录中使用它getcwd() 只会返回当前工作目录
    • 我可以在编写配置文件时使用 getcwd 并按照您的描述使用它。它没有一个函数,而是一个路径,因此配置文件将显示为: $execute_path = "path/execute.php"
    • basename(__DIR__) . "/config.php 将获取父目录或basename(__FILE__) . "/config.php 当前目录
    • 运行基本名称两次..你知道我不知道你当前的设置..但我会建议但知道安装路径使用basenamedirname配置路径然后保存设置
    猜你喜欢
    • 1970-01-01
    • 2017-03-14
    • 2014-03-02
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多