I created a login page in php named as index.php. Now when the user logs in it redirects to mypage.php. The login works fine. But also mypage.php gets open when I type the url of mypage.php even without login. I want the user must logged in to see mypage.php and incase if he changes the url in browser then an error message should be triggered. What to do?
1.localhost/index.php
2.localhost/mypage.php
In order for a login to work correctly, your “secure” page (I use that term relatively because nothing is truly secure) needs to have some sort of validation conditional. In other words you need to have some way of determining if the user is logged in.
A simple way to do this in PHP is to set a
sessionvariable when you process the user’s credentials. For example:When the user successfully logs in set a session variable like so:
Then on the mypage.php check to see if the variable is set:
Please also note, it is imperative if you are using sessions that you have
session_start();as the first line of all of your files. This allows$_SESSIONvariables that were set on a separate page to be able to be read on the current page.Hope this helps.