Intermittently unable to getUser(), resulting in multiple calls to getLoginURL
The idea is that if a user_id exists, redirect the user to https://www.example.com/XYZ/. If not, call getLoginUrl to get the user_id first. The problem is that I cannot get any user_id. Thus, the script keeps going to getLoginUrl which results in a CSRF error occurring (I get multiple State values). The problem is very random though.
after you set $user_id and keep trying until you find one of those "random" cases and observe what it is returning. You'll then need to add additional conditions to your if/then statement to handle the unexpected return, or perhaps perform a retry [with limit of course to prevent race condition].
Also depending on server and magic quotes setting, you may want to change your redirect code in the first case to the following:
I doubt that has anything to do with it or you'd see that in the URL, but hard to tell what's happening with your app and "random" are always a pain. Try and figure out what IS returning during those "random" cases and that should tell you how to handle it.