Nicole Javery
Nicole Javery

Reputation: 193

PHP File Upload Path Issue

This is the start code of my upload function,

function upload()
{
        $str_path = "../users/$this->user_name/$this->profile_image";

        if (!is_dir("../users")) {
            if (!mkdir("../users")) {
                throw new Exception("failed to create folder ../users");
            }
        }

        if (!is_dir("../users/$this->user_name")) {
            if (!mkdir("../users/$this->user_name")) {
                throw new Exception("failed to create folder ../users/$this->user_name");
            }
        }
}

There is a main folder in which all web pages are saved, that is “project” folder. I have a models folder, the class containing the upload function is in there. Then I have a process folder from where the upload function is called and it creates folders in the main “project” folder and uploads the file.

The problem is that I am also using the same function from “projects/users/process” folder. The upload path is set in upload function but the function is called from two different locations hence it creates a folder in “projects/users” folder when called from “projects/users/process”, though I need it to be creating folders and uploading always in “projects

Upvotes: 1

Views: 136

Answers (1)

Nicole Javery
Nicole Javery

Reputation: 193

Thanks to @Masiorama the problem is solved by using $_SERVER['DOCUMENT_ROOT']. The working code of the function

public function upload_profile_image($src_path) {

    $base_path = $_SERVER['DOCUMENT_ROOT'] . "/php246/project";

    $str_path = "$base_path/users/$this->user_name/$this->profile_image";

    if (!is_dir("$base_path/users")) {
        if (!mkdir("$base_path/users")) {
            throw new Exception("failed to create folder $base_path/users");
        }
    }

    if (!is_dir("$base_path/users/$this->user_name")) {
        if (!mkdir("$base_path/users/$this->user_name")) {
            throw new Exception("failed to create folder $base_path/users/$this->user_name");
        }
    }        

    $result = @move_uploaded_file($src_path, $str_path);

    if (!$result) {
        throw new Exception("failed to uplaod file");
    }
}

Upvotes: 2

Related Questions