简体   繁体   中英

Why won't this php upload script work?

I have a html form with file input named image that points to a php file with this code:

$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;
}
}

I want the filename to have the time in it instead of the original filename. I can't figure out why this won't work! All the uploaded files are named the extension. Somehow the date won't work.

Your scope is wrong for $date . You will want to either pass $date to your function or make it a global varible

$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;
    }
}

or

$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;
    }
}

This is my observation , you are having scope issues

$date =  date( "Y_m_d_H_i_s_u" );

Try if the date would always change

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;
    }
}

$date is outside of the scope of your function. There are 2 ways to fix this:

Option 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;
    }
}

Option 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);

您也可以考虑直接返回move_uploaded_file

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM