Useful PHP Tips for Beginners – Part 3

21. Validate data with php filters

Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets
try something different, called filters.

The php filter extension provides simple way to validate or check values as being a valid ‘something’.

22. Force type checking

Its a good habit.

23. Write Php errors to file using set_error_handler()

set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose

24. Handle large arrays carefully

Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :

The above thing is common when importing a csv file or exporting table to a csv file

Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.

Consider passing them by reference , or storing them in a class variable :

by doing this the same variable (and not its copy) will be available to the function. Check documentation

unset them as soon as possible , so that memory is freed and rest of the script can relax.

Here is a simple demonstration of how assign by reference can save memory in some cases

echo ‘Memory usage in MB after 3st copy (reference) : ‘. memory_get_usage() / 1000000 . ‘<br />’;
The output on a typical php 5.4 machine is :

Memory usage in MB : 18.08208
Memory usage in MB after 1st copy : 27.930944
Memory usage in MB after 2st copy : 37.779808
Memory usage in MB after 3st copy (reference) : 37.779864
So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.

25. Use a single database connection, throughout the script

Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :

Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.

Use the singleton pattern for special cases like database connection.

26. Avoid direct SQL query , abstract it

The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:

  • All values have to be escaped everytime manually
  • Manually verify the sql syntax everytime.
  • Wrong queries may go undetected for a long time (unless if else checking done everytime)
  • Difficult to maintain large queries like that

Solution: ActiveRecord

It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.

A very simple example of an activerecord insert function can be like this :

The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).

This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.

27. Cache database generated content to static files

Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.Benefits :

Benefits :

  • Save php processing to generate the page , hence faster execution
  • Lesser database queries means lesser load on mysql database

28. Store sessions in database

File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.

Storing session in database makes many other things easier like:

  • Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time
  • Check online status of users more accurately

29. Avoid using globals

  • Use defines/constants
  • Get value using a function
  • Use Class and access via $this

30. Use base url in head tag

Quick example :

The base tag is like a ‘ROOT’ url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.

Lets take an example


In home.php the following can be written :

But in ipad.php the links have to be like this :

This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.

Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php


Prakash S

Prakash S

I would like to introduce myself as a Software professional opting for the career in software industry. I'm Prakash S, a MCA graduate and trained as industry level practice for Software technology. Basically I am a PHP Developer but now days exploring more in HTML5, CSS, AngularJS and jQuery libraries.