View Full Version : You are logged in... (Short code)

03-30-2010, 10:56 PM
What is the best way going about displaying a message saying:

You are logged in as username!

If they are logged in though, but if they are not logged in then it would say:

You are not logged in. Login - Register

I want the code to be short as possible of course, don't want to go writting a load of code for such a simple thing. I would usually do it with an IF statement, but I was wondering if there was a shorter way.

03-30-2010, 11:04 PM
You could use a ternary operator like

$user_is_logged_in ? 'display logged in message ' : 'display logged out message';


03-30-2010, 11:05 PM
I have seen that kind of code before, Ima read up on it as I don't understand it fully. What exactly is the "?" for?

03-30-2010, 11:08 PM
It is called a Ternary operator, it is essentially a shortened IF statement. The question mark means "then" and the colon means "else". These two are functionality identical;

$value = ($myvar == 1) ? 'yes' : 'no';

if ($myvar == 1) {
$value = 'yes';
} else {
$value = 'no';

03-30-2010, 11:15 PM
In the PHPBB forum system they user defined vars such as S_USER_LOGGED (Logged in user). Do they have to reassign the var value everytime the page loads? :S

Or do they use something which STAYS set the entire session? Sesssion var by any chance?

03-30-2010, 11:59 PM
Similar. I imagine they use something like this;


define ('S_USER_LOGGED_IN', isset($_SESSION['username']));


echo "You are logged in.";
} else {
echo "You are not logged in. Oh dear.";


Bare in mind that defining it as a constant may look clean, but you are likely to come across a scenario where someone "logs out" half way through your script can your constant will obviously not update. I use something like this;

abstract class Session {
public static function isLoggedIn() {
return isset($_SESSION['username']);


if (Session::isLoggedIn() {
echo 'Welcome! You may have some pie.';
} else {
echo 'No pie for guests.';

03-31-2010, 12:01 AM
wtf is a adstract class?

03-31-2010, 12:08 AM
An abstract class is a type of class, that cannot be instantiated, ie: You cannot create new copies of that class.

Classes are ways of grouping your code together so that you can reuse them. In PHP they are generally regarded as an advanced feature, because you can easily write scripts that do not uses classes.

For more information, check out the php manual; http://uk3.php.net/manual/en/language.oop5.php