Search code examples
phphtmlsessiontitle

Is it good practice to send page name through sessions in php 7.1?


Hello, I started learning PHP, I set myself a goal to make a website, which would be similar to social network, as I am newbie, I don't know what is good or bad, I can code simple functions, have fundamentals of HTML, CSS, JS. But I want to learn more deeply, like what practices should I use and which I shouldn't


Here is the code of header.php :

<?php
    $page = $_SESSION['page'];
?>
    <!DOCTYPE html>
    <html>
        <head>
            <title><?php echo $page ?></title>
        </head>
        <body>
            <h3>HEADER</h3>
        </body>
    </html>
    <hr>

And here is the code of index.php :

<?php
    session_start();
    $_SESSION['page'] = "Pradinis Puslapis";
    require('tpl/header.php');
    echo "Hello World!";
    ?>
<hr>

Of course, I would include footer too, and also in index.php I would implement html code specially designed for that page, but like I wrote, I want to know If I am thinking good - to send page's name through $_SESSION variable.


Solution

  • You don't need a session in your case. When you include your header you can use your variables directly in your included script. When you have a template engine you take another way. In that case you load a template file and replace your variables and return the parsed HTML code to your PHP file and print them out.

    main.php

    $page = "Test";
    require('tpl/header.php');
    

    header.php

    <!DOCTYPE html>
    <html>
    <head>
    <title><?php echo $page ?></title>
    </head>
    <body>
    <h3>HEADER</h3>
    </body>
    </html>
    <hr>
    

    What you try here is good for learning but not really common in production. There are a ton of really good Frameworks that gives you a perfect structure and help you to prevent mistakes. For your Programm you could start with a template engine like Twig or Dwoo for example. So first you should learn the basics then you can build a website on your own or good tools. Building a good framework is really hard.