Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE)

0

I have this function:

public function showCredentialsPhoto(){
        if (isset($_SESSION["logado"]) && $_SESSION["logado"] === TRUE && (!empty($_SESSION['avatar']))):
            echo "<img class='nav-user-photo' src='<?php echo $_SESSION['avatar'];?>'/>";
        else: 
            echo "<img class='nav-user-photo' src='galeria/sistema/user.png'>";
        endif;
    }

But when I call it it gives error:

  

(!) Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C: \ wamp \ class.User.php on line 196 < p>

Why? How can I fix this?

Line 196 is this:

echo "<img class='nav-user-photo' src='<?php echo $_SESSION['avatar'];?>'/>";
    
asked by anonymous 19.07.2017 / 22:56

2 answers

3

The problem is basically to use a PHP code inside a text in PHP. You have defined double-quoted text and this tells PHP to interpret your content. What does that mean? If there is a PHP variable inside the string it will attempt to replace it with its value. You did:

echo "<img class='nav-user-photo' src='<?php echo $_SESSION['avatar'];?>'/>";

And $_SESSION is a PHP variable, so it tries to replace it with its value. In this case, the value would be an array , which already complicates replacing the value of an array within a string , but soon after you uses ['avatar'] , in order to tell you the value of the array you want. In this case, the syntax becomes invalid, PHP can not interpret correctly and triggers the error quoted. To do this, when you need to access a certain position of an array within a string , you need to do this in braces (% with%). In this way, you tell PHP that what's inside the keys should be parsed together and so PHP will understand that what you need is to access the key {} of the array avatar .

The correct one would be:

echo "<img class='nav-user-photo' src='{$_SESSION['avatar']}'/>";

Note that PHP code inside string is unnecessary and will not work. Even if you did not make this mistake, your HTML would be wrong because the internal PHP code would be sent as text. Or do the above solution using the keys, or you can use the concatenation operator:

echo "<img class='nav-user-photo' src='" . $_SESSION['avatar'] . "'/>";
    
19.07.2017 / 23:07
2

You are incorrectly using string concatenations.

See what you're doing on the line:

echo "<img class='nav-user-photo' src='<?php echo $_SESSION['avatar'];?>'/>";

Within echo you are opening a tag PHP to give another echo , when you should do something like:

echo "<img class='nav-user-photo' src=" . $_SESSION['avatar'] . "/>";

Or

echo "<img class='nav-user-photo' src='{$_SESSION['avatar']}'/>";
    
19.07.2017 / 23:07