Good and Bad PHP Code

The following is republished from the Tech Times #165.

When interviewing a PHP developer candidate for a job at SitePoint, there is one question that I almost always ask, because their answer tells me so much about the kind of programmer they are. Here’s the question: “In your mind, what are the differences between good PHP code and bad PHP code?”

The reason I like this question is because it tests more than just a candidate’s encyclopedic knowledge of PHP’s functions. Zend’s PHP certification does a good job of that (as does the test that Yahoo! issues to applicants for its PHP developer jobs, apparently).

Rather, the answer to this question tells me whether a PHP developer has, for example, experienced the pain of working with poorly-written code inherited from a careless predecessor, and whether he or she will go the extra mile to save the rest of the team from that same pain.

I don’t have a set notion of the perfect answer to the question, but I do know the kinds of things I’m hoping to hear. Just off the top of my head:

Good PHP code should be structured. Long chunks of code can be broken up into functions or methods that achieve sub-tasks with simple code, while non-obvious snippets should be commented to make their meaning plain. As much as possible, you should separate frontend HTML/CSS/JavaScript code from the server-side logic of your applications. PHP’s object oriented programming features give you some especially powerful tools to break up your applications into sensible units.

Good PHP code should be consistent. Whether that means setting rules for the names of variables and functions, adopting standard approaches to recurring tasks like database access and error handling, or simply making sure all of your code is indented the same way, consistency makes your code easier for others to read.

Good PHP code should be portable. PHP has a number of features, such as magic quotes and short tags, that can break fragile code when they are switched on or off. If you know what you’re doing, however, you can write code that works by adapting to its environment.

Good PHP code should be secure. While PHP offers excellent performance and flexibility out of the box, it leaves important issues like security entirely in the hands of the developer. A deep understanding of potential security holes like Cross-Site Scripting (XSS), Cross-Site Request Forgeries (CSRF), code injection vulnerabilities, and character encoding loopholes is essential for a professional PHP developer these days.

Once a candidate has answered this question, I usually have a pretty good idea of whether they’ll be hired or not. Of course, there’s always the possibility that an interviewee simply isn’t able to articulate these types of things, so we also have our candidates sit a PHP developer exam.

Many of the questions in this exam seem straightforward on the surface, but they give candidates plenty of opportunity to show how much they care about the little details.

The following “bad” code is a highly simplified example of the sort of thing we might put in our PHP developer exam. The question might be something like “How would you rewrite this code to make it better?”

<? echo("<p>Search results for query: " .     $_GET['query'] . ".</p>"); ?>

The main problem in this code is that the user-submitted value ($_GET['query']) is output directly to the page, resulting in a Cross Site Scripting (XSS) vulnerability. But there are plenty of other ways in which it can be improved.

So, what sort of answer are we hoping for?

Good:

<? echo("<p>Search results for query: " .     htmlspecialchars($_GET['query']) . ".</p>"); ?>

This is the least we expect. The XSS vulnerability has been remedied using htmlspecialchars to escape dangerous characters in the submitted value.

Better:

<?php if (isset($_GET['query'])) {   echo '<p>Search results for query: ',       htmlspecialchars($_GET['query'], ENT_QUOTES), '.</p>'; } ?>

Now this looks like someone we might want to hire:

  • The “short” opening PHP tag (<?) has been replaced with the more portable (and XML-friendly) <?php form.
  • Before attempting to output the value of $_GET['query'], isset is used to verify that it actually has a value.
  • The unnecessary brackets (()) around the value passed to echo have been removed.
  • Strings are delimited by single quotes instead of double quotes to avoid the performance hit of PHP searching for variables to interpolate within the strings.
  • Rather than using the string concatenation operator (.) to pass a single string to the echo statement, the strings to be output by echo are separated by commas for a tiny performance boost.
  • Passing the ENT_QUOTES argument to htmlspecialchars to ensure that single quotes (') are also escaped isn’t strictly necessary in this case, but it’s a good habit to get into.

Somewhat distressingly, the number of PHP developers looking for work that are able to give a fully satisfactory answer to this sort of question—at least here in Melbourne—are few and far between. We spent a good three months interviewing for this latest position before we found someone with whom we were happy!

So, how would you do when asked a question like this one? Are there any factors that make PHP code good or bad that you feel I’ve left out? And what else would you look for in a PHP developer?

Replay

Category: programming Time: 2007-05-25 Views: 1
Tags:

Related post

  • Indicate mixed good and bad rating 2013-04-03

    I have an app that allows users to self-evaluate decisions. At the most basic level, events will be marked positively and/or negatively indicating whether the decisions were good or bad. For example, in the realm of diet, each meal will show up as a

  • Right and left representing good and bad 2015-05-28

    I've been playing around with material design and was making an app where the user can interact with an element by either swiping it right or left (pressing it does a third thing). The idea is that swiping it to one side is the user giving feedback t

  • How do you deal with web designers who are too afraid to read and touch PHP code? 2011-01-16

    I've been hired to make a website and am working with a designer (who happens to be the guy who is in contact with the client and hired me, so no, I can't kick his ass out =) ) who's too afraid to touch into the php code, and is too newbie in html an

  • What are good and bad jitter times for a LAN 2009-11-20

    Ive just ran jperf (frontend to iperf) on our network between 2 workstations, its recorded jitter between 0.033ms and 0.048ms. Is this good or bad? Are there more variables that i would need to consider to make the decision? EDIT: TCP/IP Ethernet LAN

  • Find text, then insert linebreak and some php code across multiple files 2012-04-10

    I have a certain php code comment that appears in about 75 files across several users. This command succsessfully locates it. (I didn't bother looking for the double slashes because I wasn't sure about escaping them and they really don't matter for t

  • what will happen when two users submit same form and the php code having more than one queries will be executed on the server? 2015-10-09

    I want to ask that what will happen when two user will submit the same form and then the php code having more than one queries in more than one for loops and if statements which alter the table data will be executed? I want to know that will all the

  • Ignoring unit tests - good and bad reasons when and why? 2012-02-13

    Recently I began a new project to re-implement a core part of automation. Since it is very important, I'm TDDing it so that I can tests various basic scenarios as well as things we know the old system doesn't do. In doing this, I find myself creating

  • Is this a good "random page" PHP code? 2016-01-17

    <?php $urls = array ( "id=1.php", "id=2.php", "id=3.php" ); $random = (rand()%3); header ("Location: ".$urls[$random]); exit; ?> I suspect that it could be better, especially because I have to manually edit th

  • Division number and remainder php code 2016-06-10

    I created a function that will tell me how many times a number is divisible by another number and what the remainder of it is: <?php function divisible_times($number, $divider) { $count = 0; $remainder = $number % $divider; $num_array = range($number

  • Xcode odd behaiviour and bad rendering code 2015-05-16

    Recently I'm experiencing some odd behavior from Xcode. It jump up and down on its own, it does not render codes correctly. Like this screenshot ↓ It's driving me crazy. Have this ever occurred to anybody else? Is there a solution? P.S. this problem

  • Where do you go to read good examples of source code? 2011-01-22

    I have heard a few people say that one of the best ways to improve your coding ability is to read others code and understand it. My question, as a relatively new programmer, where do I go to find good source code examples that are not too far over my

  • Have lampp use PHP code in a directory not under /opt/lampp 2011-06-26

    I have my lampp installed in the default /opt/lampp directory and the PHP code is in the htdocs folder. Now, to edit any of the files I have to use sudo permissions and have to type my password (or use sudo -i) which I do not want to do. All I want i

  • How to find bad PHP node that makes search_cron fail? 2012-02-16

    I can't run cron, manually or automatically. I installed Cron Debug module, checked all modules, and found out that the Search module makes cron stuck. When I disable it, cron is working. I suppose the reason is one of my nodes has bad PHP code in it

  • infinite loop on page with comments after changing comments.php and header.php 2012-04-13

    I am using version 3.3.1 of wordpress but I'm following a tutorial that used version 2.7. After changing my header.php and comments.php code, I'm getting an infinite loop when I view the single post page with comments. Here is the change I made in th

  • PHP code in user session LFI filtered out 2015-05-19

    Firstly, I make the obligatory disclaimer that everything I am doing here is legitimate and pre-authorized, etc., etc. For those unfamiliar with user session local file inclusion in PHP, there's a nice example of it here in section 2.2.4: http://www.

  • How to Use PHP Code In-Page? 2015-08-08

    I am looking to create a dynamic Add-to-Cart button. The problem is that I need my server to dynamically create the "add-to-cart" URL. Currently, I have a static example built here at this link. You'll notice at the bottom of the page is a pay-p

  • Securing Apache server against slightly untrusted PHP code? 2009-12-20

    I have an unusual situation where I need multiple users to be able to upload and execute PHP code on my Apache server, but I cannot allow one user to access another user's PHP source (if concrete examples make you feel better, imagine I'm hosting a P

  • Stress testing - Is it good or bad? 2012-03-30

    First, my PC specs: Intel Core i5-2400 Intel motherboard 4 GB DDR3 RAM 2 SATA-2 7200 RPM HDD 1 DVD Writer Thermaltake 500W PSU (70% efficiency) I'm planning to buy a graphics card soon. My preference highly goes to GeForce 560/Radeon HD 6870. Their m

  • PHP Code stuck in Cache [Memcached] 2012-06-21

    Been having a bit of a problem with my site regarding our caching method and my php code not refreshing or flushing. To start, my site is on a dedicated Nginx webserver. I used W3 Total Cache for the initial caching setup. Everything was set up to ca

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 2.095 (s). 13 q(s)