Sil Sil - 7 months ago 11
HTML Question

Conditionally showing HTML without wrapping it in a PHP echo statement

I have a block of code to generate a user's profile that looks like this:

<?php
if($user_isbanned) {
echo 'User is banned.';
exit(1);
}
?>
<!-- Content to show if the user is not banned -->


This works for what I want it to do (stop the profile from appearing if the user's account is banned), but if I were to add in a footer at the bottom of the page, it would not appear on a banned user's page since the exit() statement aborted generating the rest of the page. I could reformat my code to look like this:

<?php
if($user_isbanned) {
echo 'User is banned.';
} else {
// Content to show if the user is not banned
}
?>


This would make my footer appear regardless of whether or not the user is banned, but I don't want to wrap the entire page in one large PHP echo statement. Is there anyway to prevent a certain block of HTML from appearing if a PHP condition is or is not satisfied, without putting the entire page in an echo statement?

Answer

In your first example, a footer will never be displayed. In fact, not even a closing </html> tag, that doesn't seem very desirable.

You don't have to literally echo the HTML, you could just:

<?php
    if($user_isbanned) {
        echo 'User is banned.';
    } else {
?>

<!-- html goes here -->

<?php
    }
?>

Alternatively, you could just redirect a banned user to a separate page entirely.

Comments