当上传文件为文档创建一个文件夹以进入 PHP 时


When Upload files create a folder for a document to go into PHP

基本上,当用户在我的表单上上传文件时,我不会在 docs 文件夹中创建一个新文件夹,然后在该文件夹中放置他们上传的文档。

例如:

主文件夹 = 文档/

如果用户上传文档,我希望它看起来像这样:

文档/

1/文档.jpg

因此,它会在 docs 文件夹中创建文件夹 1 并将文件放入其中。但是到目前为止,使用我的代码,它正在 docs 文件夹中正确创建文件夹 1。但是实际文档不会进入 1 文件夹,而是进入根目录。

来自我的代码的结果

文档/1

文档.jpg

它不在文档文件中,而是在实际的根目录中。

法典:

<?php
$number = 1;
$target_dir = "docs/";
$target_file = mkdir($target_dir . $number . "/") . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $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.";
        }
}
?>

更改以下内容:

$target_dir = "docs/";
$target_file = mkdir($target_dir . $number . "/") . basename($_FILES["fileToUpload"]["name"]);

对此

$target_dir = "docs/";
mkdir($target_dir . $number . "/");
$target_file = $target_dir . $number . "/" . basename($_FILES["fileToUpload"]["name"]);

mkdir返回值是一个布尔值。