PHP File Upload Creating Directory

主宰稳场 提交于 2019-12-02 04:56:36

You have to create the directory you're trying to move the file to, it won't automatically get created by move_uploaded_file.

Use mkdir(), http://php.net/mkdir, to create the directory and then move the file.

Here's an alternative ending to your script, which should do

// Create directory if it does not exist
if(!is_dir("Proposals/". $_SESSION["FirstName"] ."/")) {
    mkdir("Proposals/". $_SESSION["FirstName"] ."/");
}

// Move the uploaded file
move_uploaded_file($_FILES["upload"]["tmp_name"], "Proposals/". $_SESSION["FirstName"] ."/". $_FILES["upload"]["name"]);

// Output location
echo "Stored in: " . "Proposals/". $_SESSION["FirstName"] ."/". $_FILES["upload"]["name"];

You need to check if the directory exists, and if not, create it.

if (!file_exists("Proposals/". $_SESSION["FirstName"])) {
      mkdir("Proposals/". $_SESSION["FirstName"]);
}

You are uploading file to directory that does not exist so you need to create it first, your upload_file.php should be like

<?php
session_start();
$allowedExts = array("doc", "docx");
$extension = end(explode(".", $_FILES["upload"]["name"]));

if (($_FILES["upload"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
    if ($_FILES["upload"]["error"] > 0)
    {
        echo "Return Code: " . $_FILES["upload"]["error"] . "<br />";
    }
    else
    {
        echo "Upload: " . $_FILES["upload"]["name"] . "<br />";
        echo "Type: " . $_FILES["upload"]["type"] . "<br />";
        echo "Size: " . ($_FILES["upload"]["size"] / 1024) . " Kb<br />";
        echo "Temp file: " . $_FILES["upload"]["tmp_name"] . "<br />";

        if (file_exists("Proposals/".$_SESSION["FirstName"] ."/" . $_FILES["upload"]["name"]))
        {
            echo $_FILES["upload"]["name"] . " already exists. ";
        }
        else
        {
            // Check if directory exists if not create it 
            if(!is_dir("Proposals/". $_SESSION["FirstName"] ."/")) {
               mkdir("Proposals/". $_SESSION["FirstName"] ."/");
             }
             move_uploaded_file($_FILES["upload"]["tmp_name"],
            "Proposals/". $_SESSION["FirstName"] ."/". $_FILES["upload"]["name"]);
            echo "Stored in: " . "Proposals/". $_SESSION["FirstName"] ."/". $_FILES["upload"]["name"];
        }
    }
} else {
    echo "Invalid file";
}
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!