0

I want to create a class in php to upload files and validate file information before doing it. My class is not in the root directory. The structure is something like this:

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

My file class is like this:

<?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;
        }
    }
}

And finally my index file is:

<?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";
    }
}
?>

The problem I have is that this will only work if the relative target path is from the php file where the method is called. I can't use absolute path. How can I set my uploadFile method to work with the proper path no matter where it is called? Please be nice is one of my first projects in php.

4

3 回答 3

0

而不是 include '/../../classes/class.file.php'; 使用: include dirname(FILE).'/../../classes/class.file.php';

于 2015-07-16T00:47:47.043 回答
0

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

尝试切换到绝对文件路径。此外,realpath函数魔法常数__DIR__的使用将在这里为您提供帮助。__FILE__

于 2015-07-16T00:52:03.700 回答
0

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

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

于 2015-07-16T00:59:18.443 回答