PHP - English

Check if a user is logged in, logout



This lesson is part of an ongoing User Authentication tutorial. The first
part is here: User Authentication along with all
the files you need.

Check if a user is logged in

If you open up the file called page1.php (It’s one of the files you
downloaded from here: scripts.), you’ll see
some PHP code at the top:



if (!(isset($_SESSION[‘login’]) && $_SESSION[‘login’] != ”)) {

header (“Location: login.php”);



Again, we first start a PHP session. The IF Statement that comes next is quite
complex. But we’re testing for two things: has a user session called login been
set? And is this session a blank string?

!(isset($_SESSION[‘login’]) && $_SESSION[‘login’] != ”)

The first part is this:


To check if a session is set you can use the inbuilt function isset.
We’re using the NOT operator before it. (The NOT operator is an exclamation
mark.) So we’re saying, “IF the session is NOT set”. The session might
be set, but may have a “1” in it. We also need to check if the session
called login is a NOT blank string. If both of these things fail then we can
redirect to the login.php page, as it means that the user is not logged in.

For every page in your site, if you have the above script at the top of your
page, it will redirect a user if they are not logged in. That way, you can protect
your pages from non-members. If they are logged in, they will be able to view
the page.


Logging out

If you have a look at the code for logout.php you’ll see the following:




This is all you need to log a user out: you start a session, and then issue
the session_destroy command. All you need is a link to this page from
anywhere on your site. The link would be something like this as your HTML:

<A HREF = logout.php>Log Out</A>

When the user clicks this link, they will be taken to the page with the code
that destroys the session.



Although our login/signup scripts are by no means complete, we hope that they’ve
given you something to think about. In particular, that these types of scripts
are not as simple as you first thought. There are quite a few ready-made login
scripts that will do the job for you, but we hope that you will develop your

In the next walkthrough, we’ll script a complete survey/poll application.


Kaynak : ‘sitesinden alıntı

Yorum Yap