L'ip è valorizzato scorrettamente: $ip = $_SERVER['REMOTE_ADDR'];
Manca fclose.