When you do the test to know whether it is a .jpg file or not, you use the function substr...
substr returns a string but does not alter the string you pass as an argument.
In other words, calling substr($nomfichier, -3) will not change anything in the variable $nomfichier... And when you use it later, you will therefore still have the full name with the extension...