There's a bug in the code at the end of the loop.
/* save act point as last point */
$lastlat = deg2rad($aktlat);
$lastlon = deg2rad($aktlon);
But aktlat/lon were defined as:
$aktlat = deg2rad($track[$i2]['position']['lat']);
$aktlon = deg2rad($track[$i2]['position']['lon']);
... you've done the deg2rad conversion twice. It should be:
/* save act point as last point */
$lastlat = $aktlat;
$lastlon = $aktlon;
Not sure if that's exactly what's causing your error but it can't help! You also use a different radius for the earth in your code from the formula at the top, but that makes very little difference at all.