如何在PHP中创建文件夹并上传该文件夹中的选定文件?

时间:2018-03-31 17:16:14

标签: php html server-side

我正在尝试使用用户指定的名称创建一个文件夹并将所选文件上传到该文件夹​​,但我只能创建该文件夹而无法将上传的文件移动到该文件夹​​中。请帮帮我。

<html>
    <head>
        <title>File upload</title>
    </head>
    <body>
        <form action="#" method="post" enctype="multipart/form-data">
            <input type="file" name="file">
            <br>
            <label>Enter the folder name:</label>
            <input type="text" name="foldername">
            <br>
            <input type="submit" name="submit" value="Upload">

        </form>
    </body>
</html>

<?php
    if(isset($_POST['submit']))
    {
        $foldername=$_POST['foldername'];

        $filename=$_FILES['file']['name'];

        $tmpname=$_FILES['file']['tmp_name'];

        $result=mkdir($foldername);

        if($result)
        {
            echo "created folder";
        }
        else
        {
           echo "not created folder";
        }
        $row=move_uploaded_file($tmpname,"$result/$filename");
        if($row)
        {
            echo "succesffully uploaded";
        }
        else
        {
            echo "failed to upload";
        }
    }
?>

2 个答案:

答案 0 :(得分:0)

你有这个:

$result = mkdir($foldername);

当你尝试移动文件时,你会这样做:

$row = move_uploaded_file($tmpname,"$result/$filename");

$result将是基于mkdir成功或失败的布尔值。我想你需要的是:

$row = move_uploaded_file($tmpname, "$foldername/$filename");

答案 1 :(得分:0)

只是对您的代码进行了一些更改。 mkdir()需要foldername和权限才能创建。然后在move_uploaded_file函数中,我将$ result更改为$ foldername,即创建的文件夹

<html>
<head>
<title>File upload</title>
</head>
<body>
<form action="#" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<br>
<label>Enter the folder name:</label>
<input type="text" name="foldername">
<br>
<input type="submit" name="submit" value="Upload">

</form>
</body>
</html>

<?php
if(isset($_POST['submit']))
{
    $foldername=$_POST['foldername'];

    $filename=$_FILES['file']['name'];

    $tmpname=$_FILES['file']['tmp_name'];

    $result = mkdir($foldername,0777);

    if($result)
    {
        echo "created folder";
    }
    else
    {
        echo "not created folder";
    }

    $row=move_uploaded_file($tmpname,"$foldername/$filename");

    if($row)
    {
        echo "succesffully uploaded";
    }
    else
    {
        echo "failed to upload";
    }

}
?>