doutiaosu2310 2015-07-16 00:40
浏览 70
已采纳

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

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.

  • 写回答

3条回答 默认 最新

  • doulan0297 2015-07-16 00:52
    关注

    You're using an absolute file path for your include (with the leading forward slash) but you are using a relative file path in your files class for the upload location ($target).

    Try switching to an absolute file path. Also, the use of the realpath function and the __DIR__ and __FILE__ magic constants will help you here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题