What is the best way to monitor if a user is properly logged in/logged out?

Currently, I've put together code that does the following:

Once the user name and password are verified, two session variables are created: user name and session id. Anytime an event occurs, i.e. clicking a button, refresh, etc. I set my javascript code via onclick & onload to call a php function to verify if the two session variables are set. If they are set then the process can continue otherwise, the process ends and returns to the login page.

Is this the best way to go or is there a better way? Thoughts, suggestions appreciated. Thanks.