Are these two PHP functions equivalent?

Discussion in 'App Development' started by blueraincap, Jan 4, 2021.

  1. Say I want to print some HTML tags with a variable in it.

    I would include all html tags in an echo like this:
    Code:
    <?php
    ...
    include("abc.php");
    $title = "some title here";
    print_head($title);
    
    <?php //abc.php
    function print_head($title) { echo("
    <html><head><title>$title</title></head>
    "); }
    ?>
    A text shows below, which I don't understand why putting plain tags inside a function without print/echo will print out tags, can you explain how below works:
    Code:
    <?php
    ...
    include("abc.php");
    $title = "some title here";
    print_head($title);
    
    <?php //abc.php
    function print_head($title) {
    ?>
    <html><head>
    <title><?php echo $title; ?></title>
    </head>
    <?php
    }
     
  2. Instead of a function for all the header stuff I would put it in header.php.

    <?php
    title = "some title here";
    include("header.php");
    echo "content";
    include("footer.php");
    ?>
     
  3. Code:
    <?php //abc.php
    function print_head($title) { echo("
    <html><head><title>$title</title></head>
    "); }
    ?>
    Maybe nitpicking, but shouldn't there be a </html> after </head>, to close the <html> tag?
    I'm not familiar with php, so forgive me if this comment misses the point.
     

    • His example doesn't cover the entire page.
    • </html> will be at the bottom.
     
  4. If your title is dynamic, you should also escape the HTML in it, to avoid cross site scripting attacks.
     
  5. Yes it misses the point but it's ok; the example doesn't have </html> because print_head() can have print_x, print_y, print_z following it for doing <body> parts followed by print_footer which will close the html.
     
  6. Okay. Thanks for explaining why it wasn't in the bit of code you posted.
     
  7. 2rosy

    2rosy

  8. Sig

    Sig

    So you're missing a bunch of closing "?>" tags on your PHP script. That both ensures it won't work and makes it impossible for us to answer your question because we can't tell what it is supposed to do. You always need to have your PHP code sandwiched between a <?php and ?>. Anything outside that sandwich just gets treated as regular HTML.