0

我有一个带有名为 image 的文件输入的 html 表单,它指向一个带有以下代码的 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

4 回答 4

1

你的范围是错误的$date。您将希望传递$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;
    }
}
于 2012-05-12T22:09:17.337 回答
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;
    }
}
于 2012-05-12T22:09:28.993 回答
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);
于 2012-05-12T22:10:59.253 回答
1

也可以考虑move_uploaded_file直接退货

return move_uploaded_file($_FILES['image']['tmp_name'], $target)
于 2012-05-12T22:13:40.827 回答