How to structure a basic PHP file

When creating code, PHP gives us a huge freedom. Since PHP is compiled at runtime, it can be mixed with any text inside the file. Then, when the code is compiled, the content of the file gets to the output (usually your browser).

If you create a small project, using this technique is totally ok. The problem starts when the project starts to grow.

This article is about a small sized project with very few PHP files. In any case, readability is a very important thing. You know the case when you get back to your code after a long time to edit something, and you just are lost. To make the code readable and logically sound, there is a structure that can be used to achieve it.

If the PHP file contains HTML in it, usually it is good to separate the two. The file starts with PHP, containing all the logic needed. All the data that needs to be printed on the screen is added into variables. These variables are then used in the HTML. This clearly separates the logic from the actual data output. So the structure looks something like:

In the PHP section, where the logic is, you can also separate the logic that handles POST requests for example. It is good practice to create variables that will control such events and that hold information about these events. These variables than can control the HTML part accordingly. For example:

This makes your code clear and if needed, later you can separate the logic from the actual html. Using such a structure is beneficial for you. Since PHP is a very loose language, you are the one that needs to pay attention to such things, but you will not regret it.

6 thoughts on “How to structure a basic PHP file

  1. Hi there to all, as I am actually eager of reading this web site’s post to be updated regularly.
    It contains good stuff.

  2. Heya i am for the first time here. I found this board and I
    find It truly helpful & it helped me out a lot. I hope to provide one
    thing again and aid others such as you aided me.

  3. If you desire to grow your know-how just keep visiting this website and be updated with the newest news update posted here.

  4. Good post! We are linking to this particularly great article
    on our site. Keep up the good writing.

  5. Very nice article. I absolutely love this website. Keep writing!

  6. Aw, this was an incredibly good post. Spending some time and actual effort to make a really good article… but what can I say…
    I procrastinate a whole lot and don’t seem to get anything done.

Comments are closed.