Questions every good PHP Developer should be able to answer [closed]
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.
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
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.
"Why aren't you using something else?"
Sorry, someone had to say it :)
Is php cross-browser?
(i know, this will make laught many people, but is the more-asked question on php forums!)
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.
What is the difference between == and === and why would you want to use == at all?
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
.
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?
When a site is developed using php and it's utter crap, is it:
a) PHPs fault
b) Programmers fault
What is the best practice for escaping user input? (This question seems to come up often)
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.
"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)
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.
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 :)
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.
Explain difference of
extract()
explode()
implode()
What is wrong with the following code?
$a = 2;
function foo()
{
$a = 3;
}
foo();
echo $a;
精彩评论