75

I was going through Questions every good .Net developer should be able to answer and was highly impressed with the content and approach of this question and so in the same spirit, I am asking this question for PHP Developer.

What questions do you think should a good PHP programmer be able to respond to?

EDIT : I am marking this question as community wiki as it is not user specific and it aims to serve programming community at large.

Looking forward for some amazing responses.

NOTE : Please answer questions too as suggested in the comments so that people could learn something new too regarding the language.

Community
  • 1
  • 1
Rachel
  • 100,387
  • 116
  • 269
  • 365
  • 1
    Similar question here, about "common mistakes for PHP programmers to avoid": http://stackoverflow.com/questions/1186957 –  Jan 22 '10 at 19:16

17 Answers17

50

Admittedly, I stole this question from somewhere else (can't remember where I read it any more) but thought it was funny:

Q: What is T_PAAMAYIM_NEKUDOTAYIM?
A: Its the scope resolution operator (double colon)

An experienced PHP'er immediately knows what it means. Less experienced (and not Hebrew) developers may want to read this.

But more serious questions now:


Q: What is the cause of this warning: 'Warning: Cannot modify header information - headers already sent', and what is a good practice to prevent it?
A: Cause: body data was sent, causing headers to be sent too.
Prevention: Be sure to execute header specific code first before you output any body data. Be sure you haven't accidentally sent out whitespace or any other characters.


Q: What is wrong with this query: "SELECT * FROM table WHERE id = $_POST[ 'id' ]"?
A: 1. It is vulnarable to SQL injection. Never use user input directly in queries. Sanitize it first. Preferebly use prepared statements (PDO) 2. Don't select all columns (*), but specify every single column. This is predominantly ment to prevent queries hogging up memory when for instance a BLOB column is added at some point in the future.


Q: What is wrong with this if statement: if( !strpos( $haystack, $needle ) ...?
A: strpos returns the index position of where it first found the $needle, which could be 0. Since 0 also resolves to false the solution is to use strict comparison: if( false !== strpos( $haystack, $needle )...


Q: What is the preferred way to write this if statement, and why?
if( 5 == $someVar ) or if( $someVar == 5 )
A: The former, as it prevents accidental assignment of 5 to $someVar when you forget to use 2 equalsigns ($someVar = 5), and will cause an error, the latter won't.


Q: Given this code:

function doSomething( &$arg )
{
    $return = $arg;
    $arg += 1;
    return $return;
}

$a = 3;
$b = doSomething( $a );

...what is the value of $a and $b after the function call and why?
A: $a is 4 and $b is 3. The former because $arg is passed by reference, the latter because the return value of the function is a copy of (not a reference to) the initial value of the argument.


OOP specific

Q: What is the difference between public, protected and private in a class definition?
A: public makes a class member available to "everyone", protected makes the class member available to only itself and derived classes, private makes the class member only available to the class itself.


Q: What is wrong with this code:

class SomeClass
{
    protected $_someMember;

    public function __construct()
    {
        $this->_someMember = 1;
    }

    public static function getSomethingStatic()
    {
        return $this->_someMember * 5; // here's the catch
    }
}

A: Static methods don't have access to $this, because static methods can be executed without instantiating a class.


Q: What is the difference between an interface and an abstract class?
A: An interface defines a contract between an implementing class is and an object that calls the interface. An abstract class pre-defines certain behaviour for classes that will extend it. To a certain degree this can also be considered a contract, since it garantuees certain methods to exist.


Q: What is wrong with classes that predominantly define getters and setters, that map straight to it's internal members, without actually having methods that execute behaviour?
A: This might be a code smell since the object acts as an ennobled array, without much other use.


Q: Why is PHP's implementation of the use of interfaces sub-optimal?
A: PHP doesn't allow you to define the expected return type of the method's, which essentially renders interfaces pretty useless. :-P

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Decent Dabbler
  • 22,532
  • 8
  • 74
  • 106
  • 28
    The `strpos` question I would not be able to answer without looking up `php.net/strpos`. I feel no need to waste brain space on memorizing the utter chaos that is PHP's basic set of functions, which ones return -1, which ones false, which ones null, and which ones something entirely different. The other questions I find all right, though. – Pekka Jan 22 '10 at 17:41
  • 1
    regarding 'Cannot modify header information': If you need to generate the whole body before knowing what to put in the header, you can buffer the output using ob_* functions – Draemon Jan 22 '10 at 17:41
  • 19
    Pekka: But you *should* know that strings are zero-indexed and therefore strpos *must* be able to return zero for a found prefix. – Draemon Jan 22 '10 at 17:43
  • 1
    @Pekka: I agree more or less. I keep my PHP documentation close to myself when developing too. @Draemon: About the ob_* functions: True, but more then often this approach is considered a code smell. About the zero-indexed strings: definately. – Decent Dabbler Jan 22 '10 at 17:43
  • @Draemon: You should know that strings are zero-indexed, and as such it is a good question to test the candidate's sharp eye. True. Still. For anything I don't use daily, I ain't talking without my documentation. Not even thinking. – Pekka Jan 22 '10 at 17:48
  • 5
    Sorry but... -1. These questions check only base knowledge like access modifiers or difference between class' (static) and object's (dynamic) methods/fields. Futhermore these questions don't check any *thinking skills* (sorry, I don't know good English word to explain it). What I mean is that you don't check whether programmer is able to create *non standard* algorithms etc. – Crozin Jan 22 '10 at 18:13
  • @Crozin: I hear what you are saying. But for you're average website (which I think PHP is predominantly used for) you usually don't have to deal with very challenging algorithms (or maybe I just avoid them like the pest, because it's not my strongest point ;). But don't let me stand in your way to come up with more challenging questions. I'ld love to test myself. :) – Decent Dabbler Jan 22 '10 at 18:19
  • SELECT * is not always slower, it's even faster sometimes, because it requires less parsing ... the OOP-specific things are language agnostic ... also, they only vaguely relate with OOP ... knowing how to declare classes doesn't mean you understood OOP ... – back2dos Jan 22 '10 at 18:34
  • @back2dos: about OOP: true, I'll add some more OOP questions, but didn't feel like copying everything from the mentioned .NET question. And of course: feel free to add your own. About `SELECT *`, this is to prevent queries hogging up memory when for instance a BLOB column is added at some point in the future. – Decent Dabbler Jan 22 '10 at 18:42
  • @Crozin: Good Points, but these are solid questions for an initial filtering for candidates who have no real programming background, but sort of slipped into PHP via HTML and have not acquired proper programming basics since. As such, I find the questions okay. – Pekka Jan 22 '10 at 19:01
  • 36
    With all due respect, `T_PAAMAYIM_NEKUDOTAYIM` is a worthless test of relevant knowledge. – Sampson Jan 22 '10 at 19:04
  • @Jonathan: It was ment to be a bit toung in cheek. – Decent Dabbler Jan 22 '10 at 19:07
  • 1
    @Jonathan: Agreed. The SELECT * answer #1 thing is a trifle compared to the monumental glare of badness that is answer #2. If showed that question to someone and they answered "You shouldn't SELECT *..." before mentioning the SQL injection error I'd decide "no" for this candidate. Worrying about performance of SELECT * in the face of SQL injection is wrong-headed. @Pekka - you should know about strpos. It's a gotcha any experienced PHP dev has suffered from. If you don't know it without looking it up, you're not experienced. – jmucchiello Jan 22 '10 at 19:08
  • @jmucchiello: LOL, I agree, I caught this myself also. I was simply too lazy to turn them around. Will do it. I don't want to suggest the `SELECT *` is worse than SQL injection. – Decent Dabbler Jan 22 '10 at 19:13
  • 1
    @jmucchiello: Questions about how a function works also aren't that good, in my honest opinion. I want to know how a programmer thinks, not necessarily what he knows. There's documentation for learning how `strpos` works, I just want to know how his mind operates, first and foremost. – Sampson Jan 22 '10 at 19:40
  • @Jonathan: I agree. Questions about how a function works aren't good. There are exceptions though to every rule of thumb and in PHP, strpos is the exception to that rule of thumb. I'm not saying you should know what array_merge_recursive does. But strpos errors in PHP are so common you should know them. The question is about "experienced" PHP devs. Not 1-2 years devs. Experienced PHP devs know you don't say strpos(..) != false. No exceptions. How his mind works is orthogonal to whether he's experienced in PHP. If you don't care about experience then they don't NEED to know anything. – jmucchiello Jan 22 '10 at 19:55
  • @jmucchiello I disagree. It's a waste of brainpower to memorize the quirks and kinks of php. Rather, I remember which functions are logical, and which I should look up the documentation for when I want to use them. Principles over particulars. – user151841 Jan 22 '10 at 21:16
  • In the same vane as the T_PAAMAYIM_NEKUDOTAYIM question, you can ask what a sigil is. – markb Jan 22 '10 at 21:27
  • ...did you find some of your question on an php5 test in a website for developers jobs? ;) – Strae Jan 22 '10 at 21:48
  • 1
    @unknown - It's PHP. There are no principles to its libraries. You have to look up the particulars for EVERY function because some are func(needle, haystack) and some are func(haystack, needle). Some are array_func(&array) and some are $A = arrray_func($A). If you don't hold some of those particulars in your head, you will be as productive as a monkey banging on the keyboard. As I said, if you want experienced PHP devs, you want them because they are more productive than 100 Googling cut/paste programmers. They are more productive because they can remember the notorious function quirks. – jmucchiello Jan 22 '10 at 22:59
  • 30
    The `5 == $someVar` one is a stupid question. No idea why this coding style gets so much kudos when it's inherently flawed. – DisgruntledGoat Jan 25 '10 at 18:09
  • @DisgrundledGoat: what is inherintly flawed about it? – Decent Dabbler Jan 28 '10 at 00:59
  • @DisgruntledGoat, that's where I stopped reading and gave my -1 too. – Blindy Mar 16 '10 at 14:53
  • 1
    @fireeyedboy: One, it's ugly. It doesn't read like English. Two, it's not really needed; any modern IDE will catch this (netbeans does, at least). Three, this isn't common practice. I know some people do it, but you want to remain consistent with what the majority of the community is doing. – ryeguy Mar 18 '10 at 22:28
  • 4
    @fireeyedboy: just found this question (a year later!) and thought I would clarify my comment. ryeguy already mentioned several good reasons. My main rationale is that if you can remember to put the integer first, you can remember to check you put `==`. And you're still not 'protected' against `$someVar==$otherVar`. – DisgruntledGoat Jan 09 '11 at 16:12
  • 3
    Looking at your SQL select statement, I think the first thing wrong with it is the fact that it's syntactically wrong. The $_POST['id'] needs to be wrapped in brackets, i.e., {$_POST['id']} in order to be evaluated in double quotes. – BDuelz May 27 '11 at 03:54
  • If I were questioned these by a company, I would seriously consider whether to let them hire me or not... – nhaa123 May 05 '12 at 08:39
24

Definitively security questions !

(simple answers in this post, of course securing php web applications is far more complex)

  • how to deal with SQL injection ?

mysql_real_escape_string() for a start with MySQL. Then try to learn PDO to take advantage of prepared statements and portability across database vendors.

  • how to deal with CSRF (Cross-Site Request Forgery) ?

Add a token on every important request to secure important operations (user must have seen the form before sending the crucial request).?

  • how to deal XSS (Cross-Site Scripting) reflected and stored ?

htmlentities() is good for a start.

  • variant of XXX injections: LDAP injection, XPath injection, etc... ?

You need to know what is the "vocabulary" used by the XXX and then deduct what you need to sanitize and/or "check-and-reject".

  • what is the list of sensible functions ?

Functions which interpret PHP code (possibly included in a remote file) or which execute command on your system. A short and incomplete list could be: exec(), passthru(), system(), popen(), eval(), preg_replace()...

  • how to deal with file inclusion dangers ?
  • what is a path transversal ?
  • what are the risks associated with file upload ?

Need careful check of the parameters used when opening file or remote resources.

  • how to enforce the configuration of your PHP configuration (i.e. do you know what is the use of php.ini) ?

It is going to be long so I skip the answer, please read the PHP manual.

  • about filtering user data: what is the difference between sanitizing and check-and-refuse ?

The first one transforms the entry in something less hostile. The second one check if the entry is correct and, if not refuse it.

Kartoch
  • 7,610
  • 9
  • 40
  • 68
  • While I'll agree that you should know how to deal with SQL injection if it's appropriate, why do you say this is necessary for ALL good PHP programmers? I won't say I'm good with PHP, but did write a web app which had nothing to do with SQL and an attempt at SQL injection would have failed miserably. I know there are others doing similar work. (FYI, the app processed and graphed scientific data which didn't fit well into an SQL database.) – GreenMatt Jan 22 '10 at 17:09
  • Well, the question is a bit "vague", and because most of PHP (web) applications require a database, I have included the SQL stuff. – Kartoch Jan 22 '10 at 17:14
  • 4
    +1. although the answer to most is: use a proper framework or library ... – back2dos Jan 22 '10 at 18:34
14

"Why aren't you using something else?"

Sorry, someone had to say it :)

kprobst
  • 16,165
  • 5
  • 32
  • 53
  • 24
    I think this is a good question, actually. Developers should be able to explain why they chose one language/framework/technology over another, and the answer shouldn't be 'because I've never tried anything else'. PHP does have merits and drawbacks compared to alternatives, and contrary to popular (or maybe elitist) belief, there are valid reasons for using it. – JAL Jan 22 '10 at 18:07
  • 1
    it is a very good question ... altough i don't like PHP, i find there are plenty of good reasons to use it under certain circumstances ... – back2dos Jan 22 '10 at 18:35
  • 2
    I've definitely been asked that in interviews for PHP/LAMP jobs. I agree that it's a valid question. – markb Jan 22 '10 at 20:44
12

Is php cross-browser?

(i know, this will make laught many people, but is the more-asked question on php forums!)

Strae
  • 18,807
  • 29
  • 92
  • 131
11

I think a good question would be: how does HTTP work? Working with GET and POST data among other HTTP communications is inherent in PHP development. Understanding how HTTP works in a broader context and how PHP implements this goes a long way.

bkildow
  • 5,143
  • 4
  • 29
  • 37
9

What is the difference between == and === and why would you want to use == at all?

Michael Stum
  • 177,530
  • 117
  • 400
  • 535
  • 1
    Because if you already know the type of variable you are using there is no need for the overhead of a type check in the comparison. If you don't know what the type of your variable is then you have bigger problems than using the wrong comparator. – Mike Jan 23 '10 at 00:43
  • 1
    '===' performs faster than '==' – Ehtesham Oct 21 '11 at 12:29
  • 1
    '==' are equals but not neccesarly the same type and '===' means that they are equals and of the same type. For example, this code: will output only first, because "true" is string, and true boolean. – zuzuleinen Nov 15 '11 at 12:46
9

Explain why the following code displays 2.5 instead of 3:

$a = 012;
echo $a / 4;

Answer: When a number is preceded by a 0 in PHP, the number is treated as an octal number (base-8). Therefore the octal number 012 is equal to the decimal number 10.

Nathan Osman
  • 71,149
  • 71
  • 256
  • 361
8

No one touched on it yet but it is something that every PHP developer should be able to speak at length about: Why is register_globals bad?

markb
  • 3,451
  • 5
  • 24
  • 25
  • Actually, I'd hope it doesn't require speaking at length... one or two sentences should be enough for that dreadful idea! – JAL Jan 22 '10 at 18:03
  • 2
    `register_globals` is just as bad as a developer who uses a variable without first defining it. – Matteo Riva Jan 22 '10 at 21:06
7

When a site is developed using php and it's utter crap, is it:

a) PHPs fault

b) Programmers fault

AntonioCS
  • 8,335
  • 18
  • 63
  • 92
  • I think this is valid. I've seen a lot of new developers automatically blame the language/compiler/interpreter when their immediate assumption should be that it's them. PHP has more than its fair share of new developers so it's probably relevant. – Draemon Jan 22 '10 at 17:51
  • 1
    The programmer's fault, invariably. As long as you have a single successful implementation done with the language/platform in question. Wikipedia stands out among thousands of others. PHP might have its faults, but its success is undeniable. – kprobst Jan 22 '10 at 18:04
  • 2
    @Felix: Many people blame PHP for site X or Y that is horrible when it's obvious it's the programmers fault. PHP does what you tell it to do, it's not magical it doesn't have a mind of it's own. – AntonioCS Jan 22 '10 at 18:05
  • But where is the point that a *good PHP developer* should be able to answer this question? Every good programmer knows that if something is not working it is most probably his fault and not the language's. And if someone is blaming PHP one can still say: "Well, it is an experts language" :-D – Felix Kling Jan 22 '10 at 18:26
  • 3
    but php *is* magical: magic_quotes_gpc – Draemon Jan 22 '10 at 18:27
  • @Felix: On a company I worked one of the managers wanted to move everything to java. He said PHP was crap and didn't work. What I later found out was that he was the one the developed the company's many websites. The code was horrible, but it wasn't php's fault it was his own he just didn't want to admit it :) – AntonioCS Jan 23 '10 at 01:30
6

What is the best practice for escaping user input? (This question seems to come up often)

Matt
  • 7,022
  • 16
  • 53
  • 66
  • 10
    It's a trick question of course. It's output that needs escaping, not input. Anyone who suggests ‘sanitising’ or escaping everything in the $_GET array has Done It Wrong. – bobince Jan 22 '10 at 17:01
  • 1
    @bobince While I agree with a part of what you are getting at, what about SQL injections? Or, do you consider that a part of the output? – Jordan S. Jones Jan 22 '10 at 17:32
  • 2
    @bobince wrong. Escaping input prior to db interaction is required. Of course, if you're using stored procs like a good little developer, this becomes unnecessary (unless you're using parameters to generate and execute dynamic SQL on the SQL server, in which case you should go back and work in the tech support department) – 3Dave Jan 22 '10 at 17:40
  • @Jordan and David: SQL injections are harmless until the moment they are output (in this case to the mySQL database). You need to define "output" very broadly for that, of course. – Pekka Jan 22 '10 at 17:43
  • For SQL Injection. Simple escaping i would say "mysql_real_escape_string". Improved escaping: Prepared Statements – Fábio Antunes Jan 22 '10 at 17:44
  • I wish I could 'escape user input' – Draemon Jan 22 '10 at 17:45
  • 6
    It's not a question of input/output. You have to be aware of the context the data is moving *into*. If that's an SQL query, it must be escaped one way, if it's HTML output it must be escaped another way, if it's a URL it must be escaped yet another way, etc. The danger I think bobince was highlighting was if you escape the data at the point of entry for one context and end up using it in another later on, you're still vulnerable. – Draemon Jan 22 '10 at 17:48
  • 3
    use a framework to do that for you ... a db abstraction layer will protect you from injections ... a proper HTML rendering enging will escape output ... – back2dos Jan 22 '10 at 18:37
  • This question has no single 'right' answer. Good to see how the candidate responds. – user151841 Jan 22 '10 at 21:18
  • There is one single correct answer `http://php.net/filter_var`. – Gajus Sep 30 '11 at 09:09
6
  • When calling the "name" element of $array, which is correct?:

    • $array[name]
    • $array['name']

    Both will often work, but only the quoted form is correct. define('name', 0); and watch the bugs fly. I've seen this way too much.

  • How can you force form elements be submitted as an array?

    Append empty brackets to the name attribute: multiple <input type="checkbox" name="checkboxes[]" /> elements will be converted to an array on the server (e.g. $_POST['checkboxes'][0..n]). I don't think it's 100% PHP-specific, but it sure beats looping through $_POST for every possible 'checkboxes'.$i element.

  • mysql_, mysqli_, or PDO?

    Only one truly wrong answer here: the mysql_ library doesn't do prepared statements and can no longer excuse it's capacity for evil. Naming a function, one expected to be called multiple times per executed query, "mysql_real_escape_string()", is just salt in the wound.

tadamson
  • 8,581
  • 1
  • 18
  • 9
  • 2
    Last point: That's what foreach on arrays of values is for. Besides you shouldn't be using mysql or mysqli directly. There should be some abstraction so you can switch to pgsql (for example) at some point. – jmucchiello Jan 22 '10 at 19:14
  • @jmucchiello - Agreed on both foreach'ing and abstracting, and it's not even PHP's fault here - that's the function name in mysql's C lib. Personal taste & old scars maybe, but it still reeks of being a clumsy footnote from the "of course it's safe, I double-quoted it" days :) – tadamson Jan 25 '10 at 23:17
5

"What's your favourite debugger?"
"What's your favourite profiler?"

The actual application/ide/frontend doesn't matter much as long as it goes beyond "notepad, echo and microtime()". It's so unlikely you hire the one in a billion developer that writes perfect code all the time and his/her unit tests spotted all the errors and bottlenecks before they even occur that you want someone who can profile and/or step through the code and find errors in finite time. (That's true for probably all languages/platforms but it seems a bit of an underdeveloped skill-set amongst php developers to me, purely subjective speaking)

VolkerK
  • 95,432
  • 20
  • 163
  • 226
  • 1
    I've programmed PHP for a long time in just an editor without any problems. Debuggers are not needed. The whole Linux kernel was written without any access to a debugger. Debuggers are helpful but not at all necessary. Similarly Profilers are only needed if you actually have a time issue. I've used APD for this. But I usually have APD disabled in my php.ini. – jmucchiello May 13 '10 at 21:56
  • debuggers speed the work and not only becaese you not print values manually.the answer:xdebuger if not use zend studio and zend debugger if you use zend studio – Ben Jul 03 '10 at 23:43
5

Terry Chay has a blog post basically summarizing what every PHP developer should know and/or be expected to answer to some degree in a job interview.

http://terrychay.com/article/php-coders.shtml

I think its a great summary.

Cody Caughlan
  • 32,456
  • 5
  • 63
  • 68
4

I'd ask something like:

a) what about caching?

b) how can cache be organised?

c) are you sure, you do not do extra DB queries? (In my first stuff I've made on PHP it was a mysql_query inside foreach to get names of users who've made comments... terrible :) )

d) why register_globals is evil?

e) why and how you should split view from code?

f) what is the main aim of "implement"?

Here are questions that were not clear at all for me after I've read some basic books. I've found out all about injections and csx, strpos in a few days\weeks through thousands of FAQs in the web. But until I found answers to these questions my code was really terrible :)

Jens Roland
  • 27,450
  • 14
  • 82
  • 104
Ben Usman
  • 7,969
  • 6
  • 46
  • 66
3

Why you should never output user input directly!

Printing things like data from GET directly can lead to Cross-site scripting (XSS) vulnerabilities. Thats why you should always send input from the client through htmlspecialchars() first.

lamas
  • 4,528
  • 7
  • 38
  • 43
  • and also SQL injection, Cross-site Request Forgery (CSRF), Command/LDAP/XPath injection, include injection, file injection... – Kartoch Jan 22 '10 at 16:54
  • It is not php specific, but applies to every web application. – Residuum Jan 22 '10 at 16:58
  • 2
    It is VERY php specific, as PHP doesn't have "secure by default" spirit for developers. – Kartoch Jan 22 '10 at 17:02
  • @Kartoch: You should not assume that any system does. Even if it touts itself with that slogan. Don't trust its security over your own. – jmucchiello Jan 22 '10 at 19:15
  • @jmucchiello sorry i was not clear: PHP is one of the most vulnerable web language but I didn't mean that others are all secured. – Kartoch Jan 22 '10 at 19:22
  • I would disagree that PHP is the most vulnerable web language. Competent programmers in PHP are no more "hampered" by PHP than Django programmers are "hampered" by Django, for example. – jmucchiello Jan 22 '10 at 20:35
2

Explain difference of

extract()

explode()

implode()

Community
  • 1
  • 1
Zeishi
  • 1
  • 1
1

What is wrong with the following code?

$a = 2;
function foo()
{
    $a = 3;
}
foo();
echo $a;
Nathan Osman
  • 71,149
  • 71
  • 256
  • 361
  • The answer? Use 'global $a;' at the beginning of the function because the $a in the function is local unless the global statement is used. – Nathan Osman Jan 24 '10 at 00:11
  • 4
    Nothing's wrong. It just shows scope of the variables :) – takeshin May 23 '10 at 13:28
  • But it is clear from context that the result was not what was intended. – Nathan Osman May 23 '10 at 16:15
  • The only issue is that foo needs to return $a. Other than that, you cannot assume anything else is wrong. – Chuck Burgess Aug 14 '10 at 14:30
  • @cdb: How should the code be changed to make this a better example of the importance of properly managing scope? – Nathan Osman Aug 14 '10 at 15:20
  • 3
    Change the question and the code. Instead of saying, "What is wrong with the following code?" change it to "What will be the results of $a and why?" Change the code to the following: `$a = 2; function foo() { $a += 3; return $a; } $a = foo(); echo $a;` – Chuck Burgess Aug 14 '10 at 20:43