Kalreg
Kalreg

Reputation: 941

PHP alias of specific line in php script?

I am working with levels of security with my app and i have written a function that simply checks - depending on it's session user id what kind of priviligies he/she has. It works fine but in some pages i want to output some information if the user is superuser, and forbid to output information if user is a guest.

I do it with such a syntax:

1. <? if admin('superuser', $_SESSION['user_id'])  { ?>
2. <div></div>
3. <? } ?>

It works good but it's not elegant, and in case long code between curling brackets it messess with purity of my code. Is there a way to "alias" a line 1 and 3 to some kind of shortcut, ie

1. <? admin_superuser ?>
2. <div></div>
3. <? admin_super_user_end ?>

Maybe you have some other ideas to perform such levels of security?

The idea came from ob_start() and ob_end() commands. I am waiting for your ideas.

Kalreg.

Upvotes: 0

Views: 72

Answers (3)

Hajo
Hajo

Reputation: 849

you can include another php file that contains the corresponding html / php code with the "include" function. i also recommend to use <?php instead of just <? due short open tag issues with xml and ini settings.

Upvotes: 2

crush
crush

Reputation: 17023

you could simply set a bool at the beginning of the page:

$isSuperUser = admin('superuser', $_SESSION['user_id']);

Then, just do

<? if ($isSuperUser) { ?>
<div></div>
<? } ?>

If you don't like the $, you could define a constant:

define("SUPERUSER", admin('superuser', $_SESSION['user_id']));

Then, just do

<? if (SUPERUSER) { ?>
<div></div>
<? } ?>

Good thing about a constant is that it is global, and if using in a function, you wouldn't have to declare it global first, or pass it as an argument.

Upvotes: 4

dan-lee
dan-lee

Reputation: 14502

I would go with something like this. I think this totally acceptable.
To simplify it you just need a wrapper for your user.

<?php if ($user->isAdmin()): ?>
<div></div>
<?php endif; ?>

Upvotes: 3

Related Questions