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.

marc_s
  • 455
  • 1
  • 4
  • 15
jaec86
  • 45
  • 9

3 Answers3

0

Instead of include '/../../classes/class.file.php'; use: include dirname(FILE).'/../../classes/class.file.php';

0

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.

Scopey
  • 6,269
  • 1
  • 22
  • 34
0

If you use an autoloader then you can make all of your includes relative to your autoloader path.

Even better you can use Composer and configure your project to use PSR-0 or PSR-4 standards.

Parris Varney
  • 11,320
  • 12
  • 47
  • 76