簡體   English   中英

如何將上傳文件的$ target_dir更改為絕對路徑-網站根目錄?

[英]How to change $target_dir for uploaded file to an absolute path - website root?

這是一個WordPress插件,可以上傳圖片。 現在,圖像上傳到: http://localhost/wp-content/2018/10/image.png 我希望將它們存儲在網站的根目錄中。 在主文件夾中,有wp-content,wp-admin和其他文件之類的文件夾。

這是將文件上傳到上面指定的目標的代碼。

 <div class="wrap">
<h2>Upload files</h2>
<form action="" method="post" enctype="multipart/form-data">
Select file to upload (Supported files: .rar, .zip, .txt, .xml):
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</div>
<?php
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $target_dir = wp_upload_dir();
    $target_file = $target_dir['path'] . '/' . 
basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType 
!= 
        "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
        // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], 
$target_file)) {
            echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " 
has been 
                uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }

}



}

它應該是這樣的:/ home / user / public_html /或/ Users / username / Sites / wp /或類似的東西,但是我不知道如何實現它。

您需要添加此函數以獲取根路徑get_home_path()

更改此行

$target_file = $target_dir['path'] . '/' . basename($_FILES["fileToUpload"]["name"]);

與下面

$target_file = get_home_path() . '/' . basename($_FILES["fileToUpload"]["name"]);

暫無
暫無

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

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