Elimina le varie chiamate ad header, utilizza ob_start() + ob_get_clean() per salvare in $contents i dati che stai mandando all'output buffer.