What are the most common errors in php?
PHP makes it relatively easy to build a web-based system, which is much of the reason for its popularity. But its ease of use notwithstanding, PHP has evolved into quite a sophisticated language with many frameworks, nuances, and subtleties that can bite developers, leading to hours of hair-pulling debugging. This article highlights ten of the more common mistakes that PHP developers need to beware of. Show
Common Mistake #1: Leaving dangling array references after foreach loopsNot sure how to use foreach loops in PHP? Using references in
The problem is that, if you’re not careful, this can also have some undesirable side effects and consequences. Specifically, in the above example, after the code is executed, The main thing to remember is that Here’s an example of the kind of evasive and confusing bugs that this can lead to:
The above code will output the following:
No, that’s not a typo. The last value on the last line is indeed a 2, not a 3. Why? After going through the first As a result, when we go through the second
To still get the benefit of using references in
Common Mistake #2: Misunderstanding isset() behaviorDespite its name, This behavior is more problematic than it might appear at first and is a common source of problems. Consider the following:
The author of this code presumably wanted to check if Here’s another example:
The above code assumes that if Not. As explained,
And by the way, as a side point, if the intent in the above code really was to again check if
For cases, though, where it is important to check if a variable was really set (i.e., to distinguish between a variable that wasn’t set and a variable that was set to For example, we could rewrite the first of the above two examples as follows:
Moreover, by combining
Common Mistake #3: Confusion about returning by reference vs. by valueConsider this code snippet:
If you run the above code, you’ll get the following:
What’s wrong? The issue is that the
above code confuses returning arrays by reference with returning arrays by value. Unless you explicitly tell PHP to return an array by reference (i.e., by using So the above call to
One possible fix would be to save the first copy of the
That code will work fine (i.e., it will output
The output of this will be But to make things more confusing, consider instead the following code snippet:
If you guessed that this would result in the same “undefined index” error as our earlier As these examples demonstrate, it is not always entirely obvious in PHP whether you are dealing with a copy or a reference. It is therefore essential to understand these default behaviors (i.e., variables and arrays are passed by value; objects are passed by reference) and also to carefully check the API documentation for the function you are calling to see if it is returning a value, a copy of an array, a reference to an array, or a reference to an object. All that said, it is important to note that the practice of returning a reference to an array or an
This approach gives the caller the ability to set or get any value in the array without providing public access to the otherwise-private Common Mistake #4: Performing queries in a loopIt’s not uncommon to come across something like this if your PHP is not working:
While there may be absolutely nothing wrong here, but if you follow the logic in the code, you may find that the innocent looking call above to
As a result, each iteration of the above loop would result in a separate query to the database. So if, for example, you supplied an array of 1,000 values to the loop, it would generate 1,000 separate queries to the resource! If such a script is called in multiple threads, it could potentially bring the system to a grinding halt. It’s therefore crucial to recognize when queries are being made by your code and, whenever possible, gather the values and then run one query to fetch all the results. One example of a fairly common place to encounter querying being done inefficiently (i.e., in a loop) is when a form is posted with a list of values (IDs, for example). Then, to retrieve the full record data for each of the IDs, the code will loop through the array and do a separate SQL query for each ID. This will often look something like this:
But the same thing can be accomplished much more efficiently in a single SQL query as follows:
It’s therefore crucial to recognize when queries are being made, either directly or indirectly, by your code. Whenever possible, gather the values and then run one query to fetch all the results. Yet caution must be exercised there as well, which leads us to our next common PHP mistake… Common Mistake #5: Memory usage headfakes and inefficienciesWhile fetching many records at once is definitely more efficient than running a single query for each row to fetch, such an approach can potentially lead to an “out of memory” condition in To demonstrate, let’s take a
look at a test box with limited resources (512MB RAM), MySQL, and We’ll bootstrap a database table like this:
OK, now let’s check resources usage:
Output:
Cool. Looks like the query is safely managed internally in terms of resources. Just to be sure, though, let’s boost the limit one more time and set it to 100,000. Uh-oh. When we do that, we get:
What happened? The issue here is the way PHP’s You can at least avoid the above headfake (although it won’t itself improve your memory utilization) by instead using the Therefore, if we run the above test using
And it’s even worse than that, by the way. According to PHP
documentation, To avoid such problems, consider limiting the size of your queries and using a loop with small number of iterations; e.g.:
When we consider both this PHP mistake and mistake #4 above, we realize that there is a healthy balance that your code ideally needs to achieve between, on the one hand, having your queries being too granular and repetitive, vs. having each of your individual queries be too large. As is true with most things in life, balance is needed; either extreme is not good and can cause problems with PHP not working properly. Common Mistake #6: Ignoring Unicode/UTF-8 issuesIn some sense, this is really more of an issue in PHP itself than something you would run into while debugging PHP, but it has never been adequately addressed. PHP 6’s core was to be made Unicode-aware, but that was put on hold when development of PHP 6 was suspended back in 2010. But that by no means absolves the developer from properly handing UTF-8 and avoiding the erroneous assumption that all strings will
necessarily be “plain old ASCII”. Code that fails to properly handle non-ASCII strings is notorious for introducing gnarly heisenbugs into your code. Even simple Here’s a small checklist to avoid such problems in your code:
A particularly valuable resource in this regard is the UTF-8 Primer for PHP and MySQL post by Francisco Claria on this blog. Common Mistake #7: Assuming $_POST will always contain your POST dataDespite its name, the
(Incidentally, note the On the server side of our example, we simply dump the
Surprisingly, the result will be:
Why? What happened to our JSON string The answer is that PHP only parses a POST payload
automatically when it has a content type of Since So, for example, when processing a POST payload with a content type of
Then when we dump the
Common Mistake #8: Thinking that PHP supports a character data typeLook at this sample piece of code and try guessing what it will print:
If you answered ‘a’ through ‘z’, you may be surprised to know that you were wrong. Yes, it will print ‘a’ through ‘z’, but then it will also print ‘aa’ through ‘yz’. Let’s see why. In PHP there’s no
Yet to further confuse matters,
That’s why the sample code presented above prints the letters
That being the case, here’s one way to properly loop through the values ‘a’ through ‘z’ in PHP:
Or alternatively:
Common Mistake #9: Ignoring coding standardsAlthough ignoring coding standards doesn’t directly lead to needing to debug PHP code, it is still probably one of the most important things to discuss here. Ignoring coding standards can cause a whole slew of problems on a project. At best, it results in code that is inconsistent (since every developer is “doing their own thing”). But at worst, it produces PHP code that does not work or can be difficult (sometimes almost impossible) to navigate, making it extremely difficult to debug, enhance, maintain. And that means reduced productivity for your team, including lots of wasted (or at least unnecessary) effort. Fortunately for PHP developers, there is the PHP Standards Recommendation (PSR), comprised of the following five standards:
PSR was originally created based on inputs from maintainers of the most recognized platforms on the market. Zend, Drupal, Symfony, Joomla and others contributed to these standards, and are now following them. Even PEAR, which attempted to be a standard for years before that, participates in PSR now. In some sense, it almost doesn’t matter what your coding standard is, as long as you agree on a standard and stick to it, but following the PSR is generally a good idea unless you have some compelling reason on your project to do otherwise. More and more teams and projects are conforming with the PSR. Tt’s definitely recognized at this point as “the” standard by the majority of PHP developers, so using it will help ensure that new developers are familiar and comfortable with your coding standard when they join your team. Common Mistake #10: Misusing empty()Some PHP developers like using First, let’s come back to arrays and
And to make matters even worse, the results would have been different prior to PHP 5.0:
This approach is unfortunately quite popular. For example, this is the way To avoid these issues, the better
approach to checking for empty array structures is to use
And incidentally, since PHP casts Another example when First let’s define a
Then let’s define a
OK, now let’s see what happens when we attempt to access the
Fine so far. But now let’s see what happens when we call
Ugh. So if
we rely on Unfortunately, if a class uses the magic In contrast, if we attempt to reference a non-existent property of a
So the main point here is that the Wrap-upPHP’s ease of use can lull developers into a false sense of comfort, leaving themselves vulnerable to lengthy PHP debugging due to some of the nuances and idiosyncrasies of the language. This can result in PHP not working and problems such as those described herein. The PHP language has evolved significantly over the course of its 20 year history. Familiarizing oneself with its subtleties is a worthwhile endeavor, as it will help ensure that the software you produce is more scalable, robust, and maintainable. What are errors in PHP explain the types of errors with an example each?A "mistake" is an error caused by a fault: the fault being misjudgment, carelessness, or forgetfulness. An error message with filename, line number and a message describing the error is sent to the browser. Basically there are four types of errors in PHP, which are as follows: Parse Error (Syntax Error)
What is error explain types of errors with it's code in PHP?Error Report levels. What causes PHP fatal error?PHP Fatal Errors are coding errors so severe that the server cannot display the site properly - they are usually caused by conflicting or poorly designed extensions, . htaccess misconfigurations and things like that.
How do I fix PHP errors?Editing the php.. Log into your cPanel.. Go to the File Manager. ... . Find the “Error handling and logging” section in the php.ini. ... . Next you can set the display_errors variable to On or Off to either show the errors on your website or not.. |