How to automatically detect a user's location (city, country)?

IP2Location will provide a database of IP’s you can cross reference.
As a starting point I added the code for the class I use here