簡體   English   中英

PHP文件上傳路徑問題

[英]PHP File Upload Path Issue

這是我上傳功能的開始代碼,

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

有一個保存所有網頁的主文件夾,即“項目”文件夾。 我有一個models文件夾,其中包含上載功能的類在其中。 然后,我有一個過程文件夾,在該文件夾中調用了上傳功能,它在主“項目”文件夾中創建了文件夾並上傳了文件。

問題是我也在“ projects / users / process”文件夾中使用相同的功能。 上載路徑是在上載函數中設置的,但該函數是從兩個不同的位置調用的,因此從“項目/用戶/進程”調用時,它會在“項目/用戶”文件夾中創建一個文件夾,盡管我需要它來創建文件夾並上載總是在“項目

感謝@Masiorama,使用$ _SERVER ['DOCUMENT_ROOT']解決了這個問題。 該功能的工作代碼

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

DIR使用絕對路徑。 然后,您可以從任何地方打電話。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM