When posting PHP code, please use the board's [noparse]
..
[/noparse] bbcode tags as they make your code much easier to read and analyze.
One problem I see is that your call to [man]session_start/man won't be executed if the 'else' branch is executed, yet the 'else' branch tries to use session variables. You must call session_start() before you attempt to use session variables.
Also note that if you're using cookies to propagate the session ID, then "www.mydomain.com" and "mydomain.com" are two separate host names, and by default the cookie is set for the exact domain that was being used at the time. Thus, if your users reached the above code via "www.yoursite.com", your redirects in the form of "yoursite.com" would thus cause the cookies to be lost (meaning subsequent calls to session_start() would actually create a new, blank session).