-1

I have a php script that I wrote with a lot of help from internet and I do not fully understand what is going on. It is an upload tool which is supposed to send files uploaded to my website in a folder on the server called uploads. It works perfectly well when I use xampp, but when I run it on a remote server, that my university provided me, the script saves the files in its root folder, instead of sending them in the "uploads" folder that I created there.

I tried specifying the directory in different ways, but since it works on my computer and doesn't on the university server I got no idea what to do. The university server works with apache2 and on my computer I used the latest version of xampp for local testing.

index.html and upload.php are in the same folder and there is a subfolder called "uploads" on both of the computers.

<?php
if(isset($_POST['submit'])){
    $file = $_FILES['file'];

    $fileName = $_FILES['file']['name'];
    $fileTmpName = $_FILES['file']['tmp_name'];
    $fileSize = $_FILES['file']['size'];
    $fileError = $_FILES['file']['error'];
    $fileType = $_FILES['file']['type'];

    $fileExt=explode('.', $fileName);
    $fileActualExt = strtolower(end($fileExt));

    $allowed = array('cvs');

    if(in_array($fileActualExt, $allowed)) {
        if($fileError === 0){
            if($fileSize < 100000){
                $fileNameNew = uniqid('', true).".".$fileActualExt;
                $fileDestination = 'uploads/'.$fileNameNew;
                move_uploaded_file($fileTmpName, $fileDestination);
                header("Location: index.php?uploadsuccess");
            } else {
                echo "Your file is too big!";
            } 
        } else {
            echo "There was an error uploading your file!";
        }
    } else {
        echo "You cannot upload files of this type!";
    }
}
?>

I expected the files to be in uploads, but they go in the same folder as the script instead.

sujuka99
  • 9
  • 4

1 Answers1

1

Try adding __DIR__ before the file path:

$fileDestination = __DIR__.'/uploads/'.$fileNameNew;

This should work if the "uploads" folder and upload.php file are in the same location. Otherwise, you will have to modify the middle section of the assignment ('/uploads/') to navigate to the right directory.

Also, see this similar post with a similar problem

ARubiksCube
  • 146
  • 8
  • 1
    This works because it's an absolute path. PHP has no guarantee that the current working directory (CWD) will be the directory that the running script is in; all relative paths are calculated from the CWD. `__DIR__` is always the directory that the running script is in. – Powerlord Jun 06 '19 at 17:13
  • Well, to be more accurate, `__DIR__` is the directory that the current file is in, which is important if it's being `include`d in another script. – Powerlord Jun 06 '19 at 17:18