Turn on all error-reporting (or check the PHP error log) and make sure you're not trying to set the cookie after headers have already been sent.
Also, is it really your intention for each cookie's name to be the value of $username? Not that you can't and it might even make sense is some special case; but most typically the first parameter to setcookie() would be a string literal, the the second parameter would have the value of interest. Also, I don't think you want to use 'localhost' as the domain -- either let it be the default, or else use the domain the user would be using to request the page.
setcookie('user_name', $username, 0, '/', '.yourdomain.com'); // leading dot for domain = all sub-domains