Sorry, I got the "$first_part" line wrong. It should have been:
$first_part = $_COOKIE['Username'] . '-' . $rnd_num;
So in your code you would replace this line:
$file_name = $_COOKIE['Username']."-".str_rand(7, '123456789')."-".$_FILES['userfile']['name'];
with this:
$dot_pos = strrpos($_FILES['userfile']['name'], '.');
$first_part = $_COOKIE['Username'] . '-' . str_rand(7, '123456789');
$last_part = substr($temp_name, $dot_pos);
$file_name = $first_part . $last_part;