I have a php script which I've adapted from online tutorials.

PHP Code:
<?php
// Where the file is going to be placed
$target_path="/var/savedfiles/".$subdirectory."/";

// rename file to remove web-unfriendly characters
$OriginalFilename $FinalFilename preg_replace('`[^a-z0-9-_.]`i','',$_FILES['uploadedfile']['name']);

// rename file if it already exists by prefixing an incrementing number
$FileCounter 1;
// loop until an available filename is found
while (file_exists($target_path.$FinalFilename ))
$FinalFilename $FileCounter++.'_'.$OriginalFilename;

// Add the original filename to our target path.
$target_path $target_path $FinalFilename;

if(
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo 
"The file ".  $FinalFilename.
    
" has been uploaded";
} else{
        echo 
"There was an error uploading ".  $OriginalFilename.
    
", your file may be greater than 1Gb. Please try again!";
}
?>
The above works well except for duplicate files it adds number in front e.g. 1_filename.extension

What I want is filename_1.extension

The following almost works but the filename is lost

PHP Code:
<?php
// Where the file is going to be placed
$target_path="/var/savedfiles/".$subdirectory."/";

// rename file to remove web-unfriendly characters
$OriginalFilename $FinalFilename preg_replace('`[^a-z0-9-_.]`i','',$_FILES['uploadedfile']['name']);

$parts=pathinfo($FinalFilename);
$Extension $parts['extension'];
$FileName basename($parts,'.'.$Extension); 

// rename file if it already exists by prefixing an incrementing number
$FileCounter 1;
// loop until an available filename is found
while (file_exists($target_path.$FinalFilename ))
$FinalFilename $FileName."_".$FileCounter++.".".$Extension;

// Add the original filename to our target path.
$target_path $target_path $FinalFilename;

if(
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo 
"The file ".  $FinalFilename.
    
" has been uploaded";
} else{
        echo 
"There was an error uploading ".  $OriginalFilename.
    
", your file may be greater than 1Gb. Please try again!";
}
?>
But the filename is lost so what I get is _1.extension

What am I doing wrong?