Search code examples
phpimage-upload

File rename on upload


I have this very basic file upload script:

$prefix = "sitename";
$targetPath = "/uploads/sitename/"

$prefix = $prefix . "_";

$filename = $prefix . md5(basename($_FILES['image']['name'])) . md5(time()) . rand(11111,99999); 

if(move_uploaded_file($_FILES['image']['tmp_name '], $targetPath)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}

But I need to rename the image to $filename before it moves to the location set in $targetPath. What do I do?


Solution

  • You can specify the new filename in the second parameter of move_uploaded_file.

    Example:

    move_uploaded_file($_FILES['image']['tmp_name'], $targetPath . $filename);