PitaJ
PitaJ

Reputation: 15012

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.

Upvotes: 0

Views: 169

Answers (4)

Baba
Baba

Reputation: 95101

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

Upvotes: 1

codemonkee
codemonkee

Reputation: 3011

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

Upvotes: 1

mistapink
mistapink

Reputation: 1956

You may also consider returning move_uploaded_file directly

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

Upvotes: 1

Jeroen
Jeroen

Reputation: 13257

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

Upvotes: 1

Related Questions