Best way to structure a typical php file

OK, so I have returned to PHP after some years having been programming in other languages. I am writing a new website, and I am struggling with settling on the best way to layout a php page so that it is:

  • Readable
  • Efficient (where efficiency doesn’t compromise the other points much)
  • Easy to Refactor
  • Harder to introduce security holes
  • Harder to create bugs

Maybe I have been looking in the wrong places but I haven’t seen much on this. Is there a good practice way of doing it?

Any guidance appreciated,
Many thanks
-RT-

Hi -RT-, welcome to the forums!

I’d like to respond to your questions with a couple of my own, if I may:

  • Are you familiar/comfortable with OO programming, or are you coming from a procedural background?
  • Have you used a framework before (in PHP or another language) and were you thinking of using one for your project?

Thanks for the quick reply fretburner.

I’m comfortable with OOP and Procedural methodologies. But I’m not terribly familiar with Frameworks.

BTW, that C. A. R. Hoare quote is my desktop background :stuck_out_tongue: good choice!

Are you familiar with the MVC pattern? When writing web apps I think the most fundamental thing you can do is to make sure you have the basic separation of concerns so that your business logic, HTML, and application logic/glue code are kept separate (this is usually what people mean by MVC (Model-View-Controller) in the context of web apps these days).

If you’re unfamiliar with this approach, let me know and we can talk about it some more. I also think it can be worth picking up one of the more opinionated frameworks and working through the usual ‘getting started’ examples, as it will get you thinking along these lines.

Thanks man, I only came across it recently. It reminds me of what I should be aiming for whenever I write code :slight_smile:

Thanks,

Yeah I know about the MVC.

The basic php layout I am working with at the moment is something like this:

<?php
// inlude files you need
// put page input (post, get, etc) into handler class
// - defines what page inputs you expect
// - has regex for each input to ensure validity
// - has error message for each input if it fails validation
// - stores the inputs in a data structure - restricts access to variables if they fail validation
// - prevents invalid page inputs from propagating further in the code, narrows margin of error
// from here you only get page inputs via the handler class
// update database if needed (validate against MySQL Injection)
// get required data from database
// feed data into a data structure ready to be used in the next stage and specifically for display as content in main page
// - No html elements generated anywhere in this top php script chunk, strictly data only
// loop through data structure and convert all values with htmlspecialchars to avoid malicious html insertion
?>
<html>
  <p>Simplified html. We can create html dynamically down here now. All the data gathered from user input and database has been cleaned and validated. Only allowed to get data from the $htmlSafeDataStructure.</p>
  <p>use variable from datastructure here <?php $htmlSafeDataStructure['testVar']) ?></p>
  <ul>
     <?php
       // Insert list from data structure here
       for($i=0, $iLen=count($htmlSafeDataStructure['testArrayForList']); $i<$iLen; $i+=1) {
           echo '<li>', $htmlSafeDataStructure['testArrayForList'], '</li>';
       }
  ?>
  </ul>
</html>

So I am aiming to make it more difficult to slip up and let unvalidated variables slip through. Also all the html is together in one place making it more readable. I don’t want to be scrolling up and down to work out where bits of html have been cobbled together into a string elsewhere. I’m just concerned if there is something I have forgotten here which may cause a problem later…

-RT- :slight_smile:

Consider reading through:

It shows how a non-framework php application might be organized and then shows how Symfony 2 does it. It’s worth reading even if you not interested in using Symfony 2 as it covers many of the basics for writing php web applications.

Thanks, will give it a read now. :slight_smile:

The best way to learn the *proper way to do things quickly is to pick up a framework like Laravel or Symfony 2. Programming your own lower level code to handle common patterns such as; routing, asset management, authentication, authorization, database abstraction etc. is just a huge waste of time. Even if you did the major community driven projects will always be hundred steps in front of you in terms of code quality, support, and community. Not to mention the projects listed have amazing documentation and that is rarity for any project from my experience. No developer enjoys taking over some janky custom framework by a stubborn and/or lazy individual. I HIGHLY recommend Symfony 2 or Laravel even Zend 2 would be good. All of them have well written, clear documentation and will put you one the path to producing well architected software.

A PHP “page” or a PHP “application”? If you need to write an application and you’re thinking in terms of “page”, you’re missing something :wink:

Readable : Small, really small, smaller than that functions. Functions and objects that only do one thing, and just ONE thing. Good naming of functions/methods and variables. Your code should be readable like a small story. If you didn’t already, read the book “Clean code”. The code examples are in Java, but it’s my favorite programming book of all time.

Efficient : Well, just avoiding the beginners pitfalls (like looping for queries, etc.) should do the trick here for the majority of an app.
After that, it’s a matter of learning how to profile applications (database, CPU, code, etc.) and how to configure correctly the servers. Also, learning how to do performance tests helps a lot :slight_smile:

Easy to refactore : If you write your code in OOP, learn about S.O.L.I.D.

Harder to introduce security holes : Well, it depends vastly on the people writing the code. You can’t prevent people that don’t know what they are doing to introduce security holes. But, if your code is already well done in terms of escaping data, SQL querying, etc… People that will add new features should, normally, use the same patterns.

Harder to create bugs : Mostly the same as the “security holes” topic.

If you’re in a company with junior programmers, you need a senior to check their code (code review, all. the. time) or else they will introduce bugs and security holes. It’s impossible for juniors to write super clean code without any bugs and security holes (and that’s normal, they are just starting).

And, as other already said, using a framework will help in a couple of those points, but it’s not the only thing you need (but you should definitely use one if you’re in a company and want to code an application).

And maybe consider a templating system, it will separate HTML and PHP. The way you did it (PHP echoing HTML) is not necessarily bad because it’s just a loop, but could lead people to think that it’s ok to just put PHP code in the middle of HTML. And, IMO, a templating system will make it easier to read.

Maybe I should look into frameworks more. I have been putting it off for a number of reasons:

  • Fear it may restrict me when wanting to do something highly customised
  • Time it takes to set up and learn - probably offset many times by the savings in development time though!
  • There seems to be a new one every 10 minutes - won’t I have to migrate to a new framework when the developers drop support (fixing security bugs etc) for it?
  • Server Restrictions - I currently work from cheap shared servers with restrictions on what you can do. What if the framework is developed assuming you have more control over the server, what can be installed etc?
  • I like to learn the ins and outs of a language, I don’t want to be too abstracted from the underlying language.
  • I am actually pretty good at writing architectures, and enjoy it. I know a lot of people say that, but having a first class honours degree in Computer Science, and having written javascript/svg financial charting software (from scratch) used by a few multi-billion £ companies makes me feel relatively confident that it’s true. Just finding my feet in the PHP way of doing things.
  • Risk of implicit security holes - if hackers find a vulnerability in the framework, they can exploit pretty much any site that uses it until it is discovered by the good guys and fixed.

I do see the advantages though, in terms of a framework:

  • Already has solutions to common tasks
  • Enforces a tried and tested architecture
  • May make it easier for an employee to hit the ground running
  • Reduces the risk of being exposed to the most common security flaws
  • Helps enforce clean readable code

Many of the newer frameworks are actually based on semi-independent components. For example, Silex, Laravel and Symfony 2 all share a number of Symfony components. Instead of using a full framework, you might consider building your own using existing components for the boring parts. Composer makes it fairly easy to pull in specific components.

Here is an article describing the process:

There is a online non-github version of the same article but it is out dated so use the github.

To answer some of your concerns:

Some of the bigger players (Symfony, ZF) have been around for a fair while now, and are backed by organisations, so they’re not likely to disappear anytime soon. At the end of the day though, if your business logic is written in a way that it’s not tightly coupled to the framework, you should be able to migrate to an alternative without having to rewrite the core of your app.

Those skills are still going to come into play when creating the model layer of your app, because this is the part that’s going to change according to the requirements of each app. The framework is just the delivery mechanism… the parts that are going to remain largely (if not entirely) the same between projects. Where’s the fun in re-writing boilerplate all the time?

True, but on the other hand, any vulnerabilities are more likely to be quickly found and fixed due to the much larger number of eyes looking over the codebase. With your own code you’re relying on yourself to spot the error.

Very true. On the other hand, a hacker has to look for holes in your website specifically, so won’t have much of a reward even if they do find a hole. Sophisticated hackers are much more likely to look for holes that enable access on a whole host of sites, like those that use a popular framework.

Also ‘quickly’, well not always. The Heartbleed bug took over 2 years before it was detected.

I think it’s a balance. Security benefits and liabilities to both approaches.