coopster - 3:41 am on Feb 15, 2012 (gmt 0)
Close, but never trust user-supplied input. PHP_SELF is an index that can be manipulated by the user and needs to have, at bare minimum, strip_tags() applied.
You are correct in that you can construct the desired page upon user landing and realizing that they are not authenticated. Building the proper referer and storing it in the SESSION is a common practice to bring the user to the desired page upon authentication. The HTTP_REFERER is not reliable as users may configure their browser/computer to not submit or show the header variable. I prefer to build the referer from the page that is responding to the request. After the user has authenticated you can once again check the userid/username for proper access to said page as well.