The mathematics looks correct, in particular the formulas for u and for x and y are correct.
The error seems to be in the programming. I don't know anything about PHP, but the line
$U =(($C - $A)*($B-$A) + ($C - $A)*($B-$A))/ pow(distance($A, $B, $C),2);
and the function distance ($C,$B,$A) look very odd. Shouldn't it just be distance ($B,$A), defined as sqrt(square($B,$A) + square($B,$A))?