13. Check if directory is writable before writing any files

Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.

Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.

By doing this you get the accurate information that where is a file write failing and why

14. Change permission of files that your application creates

When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.

15. Don't check submit button value to check form submission

if($_POST['submit'] == 'Save')
{
//Save the things
}

The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :

17. Don't use the $_SESSION variable directly

Some simple examples are :

$_SESSION['username'] = $username;
$username = $_SESSION['username'];

But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.

One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict.
Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.

19. Bunch of silly tips

Use echo instead of print

Use str_replace instead of preg_replace , unless you need it absolutely

Do not use short tags

Use single quotes instead of double quotes for simple strings

Always remember to do an exit after a header redirect

Never put a function call in a for loop control line.

isset is faster than strlen

Format your code correctly and consistently

Do not drop the brackets of loops or if-else blocks.
Do not code like this :

if($a == true) $a_count++;

Its absolutely a WASTE.

Write

if($a == true)
{
$a_count++;
}

Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.

Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors.

20. Process arrays quickly with array_map

Lets say you want to trim all elements of an array. Newbies do it like this :

foreach($arr as $c => $v)
{
$arr[$c] = trim($v);
}

But it can more cleaner with array_map :

$arr = array_map('trim' , $arr);

This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the
documentation on these to know more.

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

$amount = intval( $_GET['amount'] );
$rate = (int) $_GET['rate'];

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 :

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 :

“Use the singleton pattern for special cases like database connection.”

I would avoid using singletons for a number of reasons. One being if you set it up wrong, you are tied to only one database through out your app. The second one is Unit Testing. Makes it damn near impossible to test it properly.

“One being if you set it up wrong, you are tied to only one database through out your app.”

– If needed then there should be multiple database connections , but as long as working with a single database there is no need. Its not a rule, just an approach, the use of which very much depends on the requirements.

Moreover, its possible to work with multiple databases using a single connection :

INSERT INTO `database2`.`table_name` (………

It will work even if your mysqli object is connected to `database1`

“The second one is Unit Testing. Makes it damn near impossible to test it properly.”

– Testing , development and deployment are different scenarios. The database class can be configured to be non-singleton during testing and singleton when deployed. Its just a change of configuration.

“Testing , development and deployment are different scenarios. The database class can be configured to be non-singleton during testing and singleton when deployed. Its just a change of configuration.”

Would that not defeat the entire purpose of unit testing, if you’re going to deploy different implementations to production than what you actually test ??? Sorry, but I must agree with EllisGL, singletons are a no-go if you want proper/strict unit testing. There are many more elegant and testable ways to achieve the exact same behavior without touching static properties. (giving them a parent scope and “lazy loading” the connections for example).

Next I would like to know why you state “Do not use short tags”. Is there a reason for this ? As of 5.4 they’re even enabled by default.

I personally think short tags are awful. And the support of is something I frown at. Equals sign should be an assignment, so one could read this as “Question mark equals something?!”. Are we so lazy, that writing out is too much for us to bear?

This site, binarytides.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com.