php class 路径不是调用其方法的文件路径

php class path not file path where its methods are called

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

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

我的文件class是这样的:

<?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 中的第一个项目之一。

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

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

尝试切换到绝对文件路径。此外,realpath function and the __DIR__ and __FILE__ magic constants 的使用将对您有所帮助。

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

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