使用PHP_SELF表单上载文件

时间:2013-10-27 14:43:01

标签: php forms post

我正在尝试创建一个用于存储照片的管理面板目录创建器。我已经按照教程进行了调整,但是根据我的喜好将其调整,我无法上传文件,尽管目录创建得很好。这是代码,你能暗示我做错了什么,如果我接近这个最好的方法,请?我并不完全相信设置路径为'../../../'是最好的方法。

<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
    <label>Album name:</label><span class="req">*</span>
    <br />
    <input type="text" name="album_name">
    <br />
    <input type="file" name="upload" /><br /><br />
    <input type="hidden" name="MAX_FILE_SIZE" value="5242880" />
    <input type="submit" name="submit" value="Create">
</form>

<?php
if(isset($_POST['submit'])){
    $album = $_POST['album_name'];
    if(mkdir("../images/album/" . $album, 0700, true) && mkdir("../images/album/" . $album . "/album_cover", 0700, true)){
        echo "Album directory created successfully";
    }else{
        echo "Album directory failed";
    }
}

$target_path = "../images/album/" . $album . "/album_cover/";

$target_path = $target_path . basename( $_FILES['upload']['name']);

if(move_uploaded_file($_FILES['upload']['name'], $target_path)){
    echo "The file ". basename($_FILES['upload']['name']) . " has been uploaded";
} else {
    echo "There was an error uploading the file, please try again!";
}

?>

1 个答案:

答案 0 :(得分:1)

您已将临时上传的文件移至目录,因此请使用tmp_name,而不是name

if(move_uploaded_file($_FILES['upload']['tmp_name'], $target_path)){
                                         ^

$target_path也应包含有效的文件名及其扩展名。删除basename

$target_path = $target_path . $_FILES['upload']['name'];

<强> move_uploaded_file

  

此函数检查以确保filename指定的文件是有效的上载文件(意味着它是通过PHP的HTTP POST上传机制上传的)。如果文件有效,它将被移动到目标给出的文件名。