【问题标题】:php class path not file path where its methods are calledphp类路径不是调用其方法的文件路径
【发布时间】:2015-07-16 00:40:35
【问题描述】:

我想在 php 中创建一个类来上传文件并在执行之前验证文件信息。 我的课程不在根目录中。结构是这样的:

-project
    -root
        index.php
-src
    -classes
        class.file.php
    -files
        myFile.txt

我的文件类是这样的:

<?php
Class File {
    public function uploadFile($file) {
        $target = "../files/" . basename($file['name']);
        //some additional validation
        if(move_uploaded_file($file['tmp_name']) {
            return true;
        } else {
            return false;
        }
    }
}

最后我的索引文件是:

<?php
include '/../../classes/class.file.php';
$objFile = new File();
if(isset($_POST['uploadFile']) && isset($_FILES['txtFile'])) {
    if($objFile->uploadFile($_FILES['txtFile')) {
        echo "file uploaded";
    } else {
        echo "file not uploaded";
    }
}
?>

我遇到的问题是,这仅在相对目标路径来自调用该方法的 php 文件时才有效。我不能使用绝对路径。无论在何处调用它,如何设置我的 uploadFile 方法以使用正确的路径? Please be nice 是我在 php 中的第一个项目之一。

【问题讨论】:

    标签: php realpath


    【解决方案1】:

    您正在使用绝对文件路径作为包含文件(带有前导正斜杠),但您在文件类中使用相对文件路径作为上传位置 ($target)。

    尝试切换到绝对文件路径。此外,realpath function__DIR____FILE__ magic constants 的使用将在这里为您提供帮助。

    【讨论】:

    • 谢谢我不知道这个常量。现在它按预期工作。
    【解决方案2】:

    而不是 include '/../../classes/class.file.php'; 采用: include dirname(<strong>FILE</strong>).'/../../classes/class.file.php';

    【讨论】:

      【解决方案3】:

      如果您使用自动加载器,那么您可以使所有包含相对于您的自动加载器路径。

      更好的是,您可以使用 Composer 并将您的项目配置为使用 PSR-0 或 PSR-4 标准。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-05
        • 2021-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-12
        • 1970-01-01
        • 2017-07-12
        相关资源
        最近更新 更多