Unlike Java, PHP wasn’t designed with MVC in mind, but with bigger projects MVC becomes important to keep code clean and readable. I’m sure a lot of crazy people in the class would have figured out their own MVC quick hack, but I’ll just share mine here.

  • The Model shall remain as MySQL. I’m not going to spend waste time creating beans-like objects because I personally believe beans are inefficient things for retrieving even the simplest of things. In PHP, theย mysql_fetch_assoc() function is really all that you need. The web is a stateless thing, let’s keep it that way.
  • The Controller shall be the direct PHP file that gets called, i.e. your URL links to the controller, your form submits to the controller. The controller contains purely logic.
  • The View shall be a PHP file that sits in another directory and gets called using the include() or include_once() function and contains HTML/CSS/JS and some bits of PHP such as loops for displaying content.

Also, here’s some of my personal tips when developing public-facing web applications.

  • Do create an error handling routine. You may implement this in any way you want, but I typically use an array and use the array_push() function to push errors into the array stack. If the array is empty, we know there’s no errors. But a simple array can be quite ugly, so you might want to create a data structure to take care of where exactly the error message shows.
  • Always end your files with .php. Don’t end it with .inc or .somethingelse because you will be vulnerable to expose your source code, unless you configured Apache to parse .inc files as PHP. Even so, I’d still advise to keep the suffix as .php in an event the files get deployed on another server with missing Apache config. The lesser moving parts, the better.
  • Always escape your string using mysql_escape_string() before querying the database to prevent SQL Injection.
  • Always take care of integer parsing. I like to use intval() because it doesn’t throw a fatal error. If it sees a string, it returns 0. This also prevents SQL Injection.
  • Always clean up output using htmlspecialchars() to prevent Cross-Site Scripting.
  • Never put filenames as parameters as you can be vulnerable to Path Traversal. Try to use other methods if you need to have filenames passed around, such as server-side sessions or constants.