为什么这个php上传脚本不起作用?

时间:2012-05-12 22:06:27

标签: php html file date upload

我有一个html表单,文件输入名为image,指向带有以下代码的php文件:

$date =  date( "Y_m_d_H_i_s_u" );

function upload() {

$info = pathinfo($_FILES['image']['name']);
$target = "uploads/" . $date . $info['extension'];

if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
    return true;
} else{
    return false;
}
}

我希望文件名中包含时间而不是原始文件名。我无法弄清楚为什么这不起作用!所有上传的文件都被命名为扩展名。不知怎的,日期不起作用。

4 个答案:

答案 0 :(得分:1)

$date的{​​{3}}错误。 您需要将$date传递给您的函数或将其设为全局变量

$date =  date( "Y_m_d_H_i_s_u" );

function upload($date) {
    $info = pathinfo($_FILES['image']['name']);
    $target = "uploads/" . $date . $info['extension'];

    if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        return true;
    } else{
        return false;
    }
}

$date =  date( "Y_m_d_H_i_s_u" );

function upload() {
    global $date;
    $info = pathinfo($_FILES['image']['name']);
    $target = "uploads/" . $date . $info['extension'];

    if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        return true;
    } else{
        return false;
    }
}

答案 1 :(得分:1)

这是我的观察,你有scope个问题

$date =  date( "Y_m_d_H_i_s_u" );

尝试日期总是会改变

function upload() {
    $date =  date( "Y_m_d_H_i_s_u" );
    $info = pathinfo ( $_FILES ['image'] ['name'] );
    $target = "uploads/" . $date . $info ['extension'];
    if (move_uploaded_file ( $_FILES ['image'] ['tmp_name'], $target )) {
        return true;
    } else {
        return false;
    }
}

答案 2 :(得分:1)

$ date超出了您的功能范围。 有两种方法可以解决这个问题:

选项1

$date = date( "Y_m_d_H_i_s_u" );

function upload() {
    globel $date;
    $info = pathinfo($_FILES['image']['name']);
    $target = "uploads/" . $date . $info['extension'];

    if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        return true;
    }
    else{
        return false;
    }
}

选项2

$date = date( "Y_m_d_H_i_s_u" );

function upload($date) {
    $info = pathinfo($_FILES['image']['name']);
    $target = "uploads/" . $date . $info['extension'];

    if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        return true;
    }
    else{
        return false;
    }
}

upload ($date);

答案 3 :(得分:1)

您也可以考虑直接退回move_uploaded_file

return move_uploaded_file($_FILES['image']['tmp_name'], $target)