Search code examples
phphtmlsessionformatecho

How to reference session variable in html when using echo ' ';


I am trying to reference a session variable in this line of code

<?php
     if (!isset($_SESSION['name'])) {
               echo '<a class="nav-link" href="URL">Sign Up</a>';
     } else{
               echo '<a class="nav-link" href="URL">$_SESSION["name"]</a>';
     };
?>

However can't seem to find a way for this to actually pull from the session data as it is being treated as a string and outputting literally what is there $_SESSION["name"] Is there a way around this?

thanks!


Solution

  • Try this: '.' is used for concatenation in php.

    $_SESSION['name'] = 'Ali';
    echo '<a class="nav-link" href="URL">'. $_SESSION["name"] . '</a>';
    

    This output the session['name'], which is 'Ali'.

    As a result, your code will be:

    <?php
     if (!isset($_SESSION['name'])) {
               echo '<a class="nav-link" href="URL">Sign Up</a>';
     } else{
               echo '<a class="nav-link" href="URL">'. $_SESSION["name"] . '</a>';
     };
    ?>
    

    Good Luck