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

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

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

例如:

主文件夹 = docs/

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

docs/1/document.jpg

所以它在 docs 文件夹中创建文件夹 1 并将文件放入。但是到目前为止,使用我的代码,它在 docs 文件夹中正确创建文件夹 1。但实际文件并没有进入 1 文件夹,而是进入根目录。

我的代码的结果

Docs/1

document.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 return 值为布尔值。