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条)

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64