When developing a PHP application, there are many ways you could write and develop it. Here we will be discussing the best practices to use so that you develop a well-written and well-organized program that can be easily maintained and expanded.

Code Organization
Keep PHP, CSS, and Javascript code organized by separating and logically grouping your code into separate files and then including them in the HTML page. Logically grouping your code means placing code with similar functions into the same file. This will make your code easier to read, maintain and enhance in the future.

A bad example of organizing code:

Bad Code Example

A good example of organizing code:

Good Code Example

Where the function is in the php_scripts.php file

Function Code Example

Make Use of MVC

Make use of the MVC (Model View Controller) design pattern which is one of the most popular and successfully implemented software design patterns used by software developers.

A design pattern is a reusable solution to a commonly occurring problem. It describes in detail a problem that has occurred in the past and will definitely occur in the future.” In more detail it describes the solution(s) to that problem so that the solution can be reused.

The MVC design pattern is built around three components – models, views and controllers. The model is where all business data and the rules and policies in handling that data is stored. The view is where all user interface and presentation code and logic are stored. The controller handles all interaction with the user and calls upon either the model or the view components to satisfy all user needs.

Because code is kept separate and the MVC pattern is practiced, you should organize your folders and files to reflect this. A nicely organized site hierarchy might look like this:

html
——- application
——- controller
——- includes
——- model
——- views
index.php

Use Object Oriented Principals and Practices

OOP is a programming model that organizes code and its related data into “objects” based on the principles of abstraction, encapsulation, polymorphism and inheritance. Although PHP is not an OOP language, you can still apply OOP techniques in design and programming to conceptualize entities and make your code more understandable. You will thus write less code and save time, making development much easier.

Caching

In computing, a cache is a small, temporary storage of frequently accessed data. On many computer systems, a portion of the computer’s memory is allocated as a cache for data that is used often. Since memory access is many times faster than disk access, this memory cache results in great improvements in processing speed.

To cache a page means to temporarily store the information to be used again. This is useful for pages where the data will not change often. This won’t work for a news site where the content is constantly changing, but can work for many other sites. Caching allows you to store rendered pages to be served again without fetching all the data again. Caching can also be applied for storing database queries or saved indexed pages in a crawler application.

When using a caching technique, you should also have a way to clean up the cache so that it does not get full. It’s a good idea to periodically run scheduled tasks to delete unused cached items. Check for timestamps and any cached item that is over a certain age so that it can be updated and the application can re-render the page. If possible, check for any modifications before pulling all the data and determine if you should render the page.

Remember to utilize caching to make your code more efficient and functional.

Security

You will definitely encounter malicious users who will attempt to penetrate and gain access to applications to get user information or who will attack systems to cause damage. You can use these measures to minimize the risk of being attacked.

Input Validation

Make sure to validate user input. A malicious user may try to enter invalid data in an attempt to gain access to or damage your system. For example, do not assume that if you ask the user for a date that they will give you a properly formatted and valid date. The user may type additional commands at the end of their input which may result in exposing your system. To fix this problem, check that the date they entered is valid before continuing to use that data.

Cross-Site Scripting

This computer security vulnerability allows attackers to embed client-side script into a website. The malicious script is usually hidden in data that is sent to the website. For example, if a website asked a question such as “What is your favorite movie?” the attacker would send, embedded in their response, code to steal names and emails. When another user views the attacker’s response on the website, they unwittingly execute the malicious embedded code thus compromising their username and email.

To prevent this type of cross-scripting attack, check user inputs and responses for HTML keywords and tags

Access Control

When certain parts of your application are restricted, this can produce vulnerabilities and expose sensitive information. Check the user’s credentials for each and every page they go to or any requests received. Have a way to configure your access control so that it is automatically done by your system. Also, don’t keep old files in the web directory by renaming them .bak or .old—instead, use a source version control tool to keep track of changes.

Protect the Session ID

Each session for the user is given a unique ID. A session begins when you start the PHP session in your code with the start_session() method. This method automatically generates a session ID. However, if someone knows the ID, a malicious user can hack into your session and see confidential information. Always recheck the session ID when performing highly secure operations, such as changing a password, enter credit card information, or changing address. Ask the user to enter their password again before making a change.

SQL Security

If you are using user input to build an SQL query statement, a malicious user could insert certain SQL keywords and characters into his response which will then become part of the SQL query statement you are building (a hacking technique known as “sql injection”). Without your knowing it, your SQL query statement has been drastically altered to achieve the attacker’s devious intent.

Again, input validation is the best way to prevent this type of attack. Check the user’s input for any SQL keywords and special characters, especially escape sequences. Check the PHP configuration file (file extension .ini) for the magic_quotes_gpc configuration. If it’s turned on, you can utilize stripslashes() and addslashes() to properly format the query.

Error Reporting

The configuration of display_errors should be set to 0. If it is set to 1, then all detailed error reporting will be displayed on the screen for the user to see. This means that the user now has some insight into your application. They do not need to know this information.

Set the error_log to 1 so that all error reporting goes to a log file and you should periodically check this log file. If there is an error when the user is in the application, you can simply make a general message so they know something went wrong and redirect them to another page.

Use HTTPS

When handling secure personal information, such as credit card numbers and passwords, use https instead of regular http so that the data gets encrypted. The ‘s’ in https stands for secure. When you see https you know that you are in a secure page. If you use http for transmitting secure data, it can be exposed more easily.

Conclusion

Many of the PHP tips we’ve discussed today can apply to any programming language. Big challenges in application development lie in writing good code, caching data, and capturing and remedying security flaws. Be sure to use these easy tips in your PHP development.

2 thoughts on “Easy PHP Tips

  1. hi

    i am using flash cs4 and started watching your videos on building an mp3 player. i thought they were easily understandable. is there a complete set of videos that you have from start to finish.

    thanks
    bill

Leave a Reply

Your email address will not be published. Required fields are marked *