PHP文件根据唯一用户ID上传到目录

时间:2012-08-08 20:20:40

标签: php file variables upload directory

我似乎无法让目录在文件路径中使用用户 id变量($ id)。直接上传到成员文件夹是没有问题的,但是一旦我尝试在注册期间根据用户ID创建的唯一文件夹,我就被封锁了。

到目前为止,这是我拼凑的内容:

<?php
$id = $_SESSION['id'];
$udir= "members/.$id./";
$ufile = $udir . basename($_FILES['file']['name']);
$allexts = array("jpg", "jpeg", "gif", "png");
$ext = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 2000000)
    && in_array($ext, $allexts)){
    if (move_uploaded_file($_FILES['file']['tmp_name'], $ufile)) {
        echo "File upload was successful.";
    } else {
        echo "An error has occured. Please try again.";
    }
} else {
    echo "Invalid file type. Please try again.";
} ?>

1 个答案:

答案 0 :(得分:0)

试试这个

if(!is_dir($udir)){

    mkdir("members/".$id, 0777);
}

您的代码: -

<?php
$id = $_SESSION['id'];
$udir= "members/".$id."/";

if(!is_dir($udir)){

    mkdir("members/".$id, 0777);
}

$ufile = $udir . basename($_FILES['file']['name']);
$allexts = array("jpg", "jpeg", "gif", "png");
$ext = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 2000000)
    && in_array($ext, $allexts)){
    if (move_uploaded_file($_FILES['file']['tmp_name'], $ufile)) {
        echo "File upload was successful.";
    } else {
        echo "An error has occured. Please try again.";
    }
} else {
    echo "Invalid file type. Please try again.";
}