Home > Software engineering >  PHP Syntax Error when trying to use a function
PHP Syntax Error when trying to use a function

Time:08-16

Recently I started working with PHP and creating functions to make stuff easier for me.

I just created a simple function that I can use in a lot of files so it checks the users 'permission group' (e.g. Admin).

This is the code that was used:

function staffCheckStart() {
    echo "if ($_SESSION['role'] == 'Admin' OR $_SESSION['role'] == 'Owner'):";
}

function staffCheckEnd() {
    echo "endif";
}

This is how the function is called in another document.

<?php staffCheckStart(); ?>
        
   <iframe src="gif.com" width="276" height="480" frameBorder="0"  allowFullScreen></iframe><p><a href="gif.com">via GIPHY</a></p>

<?php staffCheckEnd(); ?>

And in return I get this error.

In my head this all works out because I just want the code to echo the PHP line that I've written in my function. The only reason I tried to use functions is because I first of all want to make it easier and make the code look clean as writing things like this over and over really drives me insane. It returns me a syntax error but I have no clue what it is.

CodePudding user response:

First, you can't echo PHP code to browser to work, it just make code like string. Second, from what I saw in your code, I think you want show iframe when role is "Admin" or "Owner". So, I suggest you to make like this

<?php if ($_SESSION['role'] == 'Admin' OR $_SESSION['role'] == 'Owner'): ?>
        
   <iframe src="gif.com" width="276" height="480" frameBorder="0"  allowFullScreen></iframe><p><a href="gif.com">via GIPHY</a></p>

<?php endif; ?>

CodePudding user response:

Echoing PHP code will not substitute the code back into the script to be executed. So your whole approach is misguided.

The function should return the result of the condition, and then you can call it in an ordinary if statement.

<?php
function staffCheck() {
    return $_SESSION['role'] == 'Admin' OR $_SESSION['role'] == 'Owner';
}

if ($staffCheck()): ?>
   <iframe src="gif.com" width="276" height="480" frameBorder="0"  allowFullScreen></iframe><p><a href="gif.com">via GIPHY</a></p>
<?php endif; ?>
  •  Tags:  
  • php
  • Related