doupo6967 2018-04-06 08:00
浏览 128
已采纳

如何在HTML标记中使用php参数?

So I have tried researching this before jumping into asking this question. Given that I have an index.php, and a cookie which stores the username, saved as $name, most answers tell me its simple to do this:

echo '<h3>'.$name.'</h3>'

But this doesnt work for me, and I assume its because im doing strange syntax for an if statement first, and I want to use the parameter within this if statement. My exact code looks more like this:

<?php 
  //store the cookie
  $name=$_COOKIE['user'];
  //check that it is set
  if(isset($_COOKIE['user'])): 
    <section id="login">
      <h1> Welcome</h1>
      echo '<h3>'.$name.'</h3>';
    </section>
  else: //prompt to login
  endif;
?>

It is meant to show a welcome message to a user that is logged in, adressing them by name, otherwise prompt the user to login.

So my question is: Why doesn't the parameter reflect at all? (shows nothing when the page is loaded) and How can I get this to work as intended?

ps. Please don't worry about the security risk of using cookies to do this etc. It is purposefully vulnerable.

pps. I am 100% sure the cookie is set, I viewed it with a cookie browser.

  • 写回答

4条回答 默认 最新

  • douguiyan9164 2018-04-06 08:02
    关注

    It doesn't work because the previous two lines are invalid PHP so it would throw an error and stop working.

    If you want to use the echo approach then the correct syntax would be:

      echo '<section id="login">';
      echo '<h1> Welcome</h1>';
      echo '<h3>'.$name.'</h3>';
    

    It is important to never insert external data as if it were raw HTML. This can render you vulnerable to XSS attacks. Treat the input as plain text and convert it to HTML before outputting it into an HTML document.

    $name_html = htmlspecialchars($name);
    echo '<section id="login">';
    echo '<h1> Welcome</h1>';
    echo '<h3>'.$name_html.'</h3>';
    

    You can make the code easier to read by using variable interpolation:

    $name_html = htmlspecialchars($name);
    echo '<section id="login">';
    echo '<h1> Welcome</h1>';
    echo "<h3>$name_html</h3>";
    

    And when outputting large chunks of HTML, it is easier to just drop out of PHP mode entirely:

    $name_html = htmlspecialchars($name);
    ?>
    <section id="login">
    <h1> Welcome</h1>
    <h3><?=$name_html?></h3>
    <?php
    

    Aside

    Check to see if the cookie is set before you try to use it, not afterwards!

    if(isset($_COOKIE['user'])): 
      $name=$_COOKIE['user'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 MATLAB四叉树处理长方形tif文件
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了