Are You Making These 10 PHP Mistakes?
Feb 2nd in Articles by Glen Stansberry
One of the best things about PHP is that it's a great language to just "dive into", thanks to its wide-ranging popularity. Anyone with the ability to hit "Search" on Google can quickly create a program. However, this also lends to a major criticism of PHP: it's almost too easy to find and reproduce bad code.
Here are 10 PHP mistakes that any programmer, regardless of skill level, might make at any given time. Some of the mistakes are very basic, but trip up even the best PHP programmer. Other mistakes are hard to spot (even with strict error reporting). But all of these mistakes have one thing in common: They're easy to avoid.
Take the time and make sure that your PHP is secure, clean and running smoothly by checking your site for these common PHP blunders.
1. Single quotes, double quotes
It's easy to just use double quotes when concatenating strings because it parses everything neatly without having to deal with escaping characters and using dot values. However, using single quotes has considerable performance gains, as it requires less processing.
Consider this string:
# $howdy = 'everyone';
# $foo = 'hello $howdy';
# $bar = "hello $howdy";
$foo outputs to "hello $howdy" and $bar gives us "hello everyone". That's one less step that PHP has to process. It's a small change that can make significant gains in the performance of the code.
2. Semicolon after a While
It's funny how one little character can create havoc in a program, without even being reported to the PHP error logs! Such as it is with semicolons and While statements.
Codeutopia has an excellent example of this little error, showing that these nasty errors don't even get reported (even to E_ALL!), as it quietly falls into a silent loop.
$i = 0;
while($i < 20); {
//some code here
$i++;
}
Omit the ; after the while statement, and your code is in the clear.
3. NOT Using database caching
If you're using a database in your PHP application, it is strongly advised that you at least use some sort of database caching. Memcached has emerged as the most poplar caching system, with mammoth sites like Facebook endorsing the software.
Memcached is free and can provide very significant gains to your software. If your PHP is going into production, it's strongly advised to use the caching system.
4. Missing Semicolon After a Break or a Continue
Like #2, a misused semicolon can create serious problems while silently slipping off into the shadows, making it quite difficult to track the error down.
If you're using a semicolon after a "break" or "continue" in your code, it will convince the code to output a "0" and exit. This could cause some serious head scratching. You can avoid this by using braces with PHP control structures (via CodeUtopia).
5. Not Using E_ALL Reporting
Error reporting is a very handy feature in PHP, and if you're not already using it, you should really turn it on. Error reporting takes much of the guesswork out of debugging code, and speeds up your overall development time.
While many PHP programmers may use error reporting, many aren't utilizing the full extent of error reporting. E_ALL is a very strict type of error reporting, and using it ensures that even the smallest error is reported. (That's a good thing if you're wanting to write great code.)
When you're done developing your program, be sure to turn off your reporting, as your users probably won't want to see a bunch of error messages on pages that otherwise appear fine. (Even with the E_ALL error reporting on they hopefully won't see any errors anyway, but mistakes do happen.)
6. Not Setting Time Limits On PHP Scripts
When PHP scripts run, it's assumed that they'll eventually finish in a timely manner. But every good programmer knows that nothing should be assumed in a piece of code. Nothing makes a program crankier than an unresponsive script.
You can get around this issue by simply setting a time limit on the script (set_time_limit). While it may seem like a trivial thing, it's always clever to prepare for the worst.
7. Not Protecting Session ID's
A very common PHP security mistake is not protecting session ID's with at least some sort of encryption. Not protecting these Session ID's is almost as bad as giving away a user's passwords. A hacker could swoop in and steal a session ID, potentially giving him sensitive information. MT Soft an example of how to protect Session ID's with sha1:
if ($_SESSION['sha1password'] == sha1($userpass)) { // do sensitive things here
}
Adding the shai1 to the ($userpass) gives an added bit of security to the session. Sha1 isn't a bulletproof method, but it's a nice barrier of security to keep malicious users at bay.
8. Not Validating Cookie Data
How much trust do you put into cookies? Most people don't think twice about the seemingly-harmless bit of data that's passed by a cookie. The name "cookie" itself is associated Milk, nap time and Santa, for crying out loud! How could a cookie possibly harmless?
If you're not validating cookie data, you're opening your code to potential harmful data. You should use htmlspecialchars() or mysql_real_escape_string() to validate the cookie before storing it in a database.
9. Not Escaping Entities
Many times PHP programmers are too trusting with data, especially data generated by user. It's imperative to sanitize data before it goes into any sort of storage, like a database.
Source Rally shows us how to correctly escape entities in things like forms. Instead of using this:
echo $_GET['username'];
You can validate the data by using htmlspecialchars() (or htmlentities()) like so:
echo htmlspecialchars($_GET['username'], ENT_QUOTES);
10. Using Wrong Comparison Operators
While comparison operators are an extremely basic part PHP programming, mixing these up in your code is certain to bork your program. As the German proverb states, the Devil is in the details.
Being familiar with the often-misused operators like =, ==, != , are absolutely critical to PHP programming. Taking the time to really understand the differences will greatly speed up your programming and yield less bugs to debug.
User Comments
( ADD YOURS )Mason Sklut February 2nd
I have made a few of those mistakes before, especially #4.
Making sure your applications are secure has become more and more of a big deal. With an increasing number PHP-based web apps coming about, this is valuable information to have.
Thanks,
( )Mason
Luis Lorenzo February 2nd
I think there is a mistake in #1:
” $foo outputs to “hello $howdy” and $bar gives us “hello everyone” ”
Should be:
” $bar outputs to “hello $howdy” and $foo gives us “hello everyone” “
( )Dan February 2nd
Actually you made your first PHP mistake : )
“$foo outputs to “hello $howdy” and $bar gives us “hello everyone”.”
Its actually the other way around:
$foo > hello everyone
( )$bar > hello $howdy
mary February 2nd
Thanks for these! I am constantly trying to learn best practices and see the common errors I make. This will help a lot!
( )Jonny February 2nd
isnt #1 the wrong way round? I though double quotes evaluated variables in the string, so that $foo would output hello everyone.
( )Dan February 2nd
Just so I don’t look crazy when you change it later : )
Here’s the original code I was referring to above:
$howdy = ‘everyone’;
( )$foo = “hello $howdy”;
$bar = ‘hello $howdy’;
demogar February 2nd
Really great list!
.
( )I’ve made some of theme in the past, but not anymore
It’s great to see the DB cache on the list
DKumar M. February 2nd
No, I’m Not
( )Luke Brookhart February 2nd
#1 is backwards. $foo prints “hello everyone”, and $bar prints “hello $howdy”. Therefore, you’d have to escape the single quoted string.
( )Sean McArthur February 2nd
The first error has a typo. ‘hello $howdy’ will output ‘hello $howdy’.
You need concatenation. ‘hello ‘ . $howdy;
( )Foobar February 2nd
‘hello $howdy’ will actually print “hello $howdy” and “hello $howdy” will print “hello everyone”.
( )“” => preprocessed output
” => plain output
Wouter Van den Neste February 2nd
Nice article!
( )The DB caching is indeed something to take in consideration
dave February 2nd
The biggest issue with php is that all these newbie or graphic artists go right to php and skip the things that they really need to know first like creating basic & proper html & css and then working their way up. And then expecting them to write proper OOP php code is completely a joke until they are a bit seasoned in coding and have a solid understanding of how the whole base code + mvc works, it’s not something you can learn in a weekend of googling. Most all these open source php apps are horrible nightmares of coding & I stay far away from them.
Beginning coders need to not worry about whats cool and learn to do it right, actually, I take that back since I make about 80k a year off of redoing or fixing the disasters that these people make, keep it up you are making me lots of $$$$$!
I’m sure this will upset some of you but it is the truth.
( )Skip D February 2nd
I really like nettuts and appreciate the article, but there are a few errors and misunderstandings/mis-applied bits of information in this article (single quotes vs. double quotes, data sanitizing . . .)
( )AgentSmith February 2nd
Sean, I think you’re mistaken. The first “error” is indeed wrong, but he simply mixed the two variables up. If you change $foo with $bar in the explanatory sentence the code example is correct and I’m sure it never meant to include any kind of concatenation.
( )FireDart February 2nd
Nice list, good job!
-FireDart
( )Nouman Saleem February 2nd
I don’t know yet – I’m still waiting for the video series ;D
( )Dave Doyle February 2nd
Uhhh… you got it backwards in the first example. Double-quotes interpolate variables, single quotes do not.
( )Randy February 2nd
Thanks! I am in the process of learning PHP and this reference will come in handy! So great to wake up every morning and see what’s new on NETTUTS rss feed on my iGoogle.
( )CloudedVision February 2nd
I generally don’t even store passwords and such in the cookies, even with encryption like sha1. I usually give the user a randomly generated ID (Either as a session or a cookie) and store/retrieve data from a database with it as an identifier. Doesn’t put the user’s password at risk and also makes your scripts more secure. Also, since no one can meddle with the db (as opposed to almost anyone can meddle with cookies), you can just store the user ID for faster code.
( )Unreal Media February 2nd
Great article. There were a few things I didnt know there. Although most I simply found out the hard way :p
( )Mike McLin February 2nd
As Sean already pointed out… Mistake #1 is not correct. The results of $foo and $bar are mixed up. [as of typing this comment]
( )insic February 2nd
nice article. Maybe in my earlier stage in using php. Yes i do made this mistakes. And thanks for making me more aware of these things.
( )Brian Cook February 2nd
uh, doesn’t the performance link in #1 (http://phpbench.com/) directly contradict the assertion that single quotes are faster? There is negligible difference in their single-vs-double test.
( )Phd Pete February 2nd
using PHP in the first place was the biggest mistake
( )John Lanz May 31st
Why did you say that?
( )Ersin Demirtas February 2nd
Thank you very much, helpful article.
( )David Singer February 2nd
It should really be:
$foo = “hello {$howdy}”;
Most coding style guides recommend the {} for readability/safety.
( )Meshach February 2nd
Great Article!
( )Talej February 2nd
Fairly un-insightful article, I have to say… I’ve worked with a lot of php developers and I’ve never once heard of anyone making some of those mistakes…
( )Steve February 2nd
Yikes, that typo on the #1 point will confuse many. Please fix.
( )M.A.Yoosuf February 2nd
great man, but i never misses those semicolon and quotes becouse im using latest Netbeans IDE
its simply superb!
( )Christian February 2nd
Its missing a ; in the first one!
( )begs February 3rd
I do it like
$foo = “hello “.$howdy;
thats best readability, cause you separate php and html for the reader’s eyes.
( )erlando February 3rd
The “Semicolon after while” while correct isn’t exactly a PHP specific mistake. Do the same in any C-like language and you will have the same result.
It should be quite easy to find using common debugging techniques instead of just relying on E_ALL.
( )netzmeister February 3rd
Good list … there are some more ..
( )David Singer February 3rd
#7 is wrong (not secure). If your code was open source (or leaked) then a user would know that all you were doing is checking the SHA1 of their username. Since SHA1 is a public algorithm they could reproduce this with little effort.
A better way might be like this:
if ($_SESSION['sha1password'] == sha1($userpass . SECRET)) {
// do sensitive things here
}
Where SECRET is a defined constant that changes for each installation. You should probably compile in hash() and use sha256 as well if your supper paranoid, and call session_regenerate_id() religiously.
( )yongfook February 3rd
I think saying anyone NOT using caching is making a “php” mistake is a bit misleading… perhaps you were grasping at things to put in the list.
Caching is and always will be something that needs to be considered case-by-case. Caching doesn’t equal a performance gain, it simply removes a potential bottleneck (your database server) and creates another one (your disk I/O). If you are on some slow, shared server with poor disk I/O speeds and are hoping to implement a caching system that expires frequently, you’ll probably thrash your server to death for zero performance gain.
And if you are an individual with the technical capacity to set up memcached on your server, then you probably don’t need to be told to use memcached. Sorry, I really find point (3) quite redundant.
If you wanted to add in a point about databases to your list, how about suggesting that people who are making wordpress themes/plugins and whatnot actually learn (and care) about optimising their SQL queries instead of doing silly things like looping through code and making dozens of SELECT * queries per page just for one bit of functionality. The real reason that so many wordpress databases die isn’t because your blog needs caching, it’s more likely because your theme needlessly makes a hundred badly-written queries to the database each time it is rendered, thanks to all your bells and whistles plugins.
( )Lamin February 3rd
#2 could easily be avoided if you where using a goof IDE but because PHP does not compile like C# or Java it’s an easy mistake to make.
( )Thomas Winsnes February 3rd
I’m a bit surprised by some of your conclusions.
#1
The difference between using double quotes and single quotes is so minimal that there is really no difference. Using double quotes allows you to include variables in the string that will be converted without combining string. But you should combine strings! It makes you code a lot easier to maintain, as it is really easy to miss a variable that is hidden inside a string, especially when you have code highlighting on.
$foo = “bar” . $variable;
$bar = ‘foo’ . $variable;
Use either one, doesn’t matter which
#2
Done that one a few times myself. Hard to notice
Good one
#3
Database cashing? memcache? What does this have to do with php? Hey, if you use an external database server, these won’t even be on the same box as the php is executed
#4
If you don’t put a semicolon after break or continue you get a compile error. They both allow an optional attribute which designates how many levels up they will affect
#5
Good point, E_ALL will list all errors/warnings/notices. But please remember to turn it off when you go live. Or those logs of your will be really big!
#6
Handy for when your database is overloaded and times out
#7
I’m at a loss on how hashing your sessionID will have a security impact. All I see it as is wasted processing power. The sessionID is sent to the users computer, usually as a cookie. The hacker needs to get the contents of this cookie to get the sessionID.
example of how this will fold out:
Hash sessionID -> send session cookie
recieve session cookie -> hash session ID -> compare to session cookie
Since the hacker would send the same session cookie as the user, there wouldn’t be a difference if it’s hashed or not
I think you’re confusing hashing of passwords with sessions. But passwords should NEVER be send with cookies. Hashed or not
#8 and #9
Always assume users are evil and the next step they will take after breaking your site is to hunt you down and kill you. Make sure you defend your site so they can’t get to the next step!
#10
( )Valid point, but I kind of find it to be a bit of a last ditch effort to hit 10 points. It’s pretty obvious that you will have to user the correct logical structure. And you forgot about ===
Jani Hartikainen February 3rd
You could have at least credited me for #2 and #4… You even copied the whole code example from my post for #2.
At least you did bother telling that my site has a “good example”…
- Jani Hartikainen, codeutopia.net
( )Jonas February 3rd
memcached is great if your site gets a ton of traffic and your database server is suffering from the load, but claiming that you should always use memcached in a production environment is a bit much. Normal SQL databases have built-in caching mechanisms, and there’s no reason to spend extra time coding memcached stuff when you can keep it all in the SQL database (unless, of course, you run a high-traffic site and your database is suffering from load issues that cannot be resolved with normal optimizing (indexing, etc.)).
( )Magda February 3rd
great article, thank you!
( )Sean Delaney February 3rd
Nice!
( )Charlie February 3rd
#7 didn’t make sense to me, and I’m happy to see someone else thinking the same way. (Thomas Winsnes, above).
The session id is a random-looking group of digits already – it has no inherent meaning. Encoding it will just change it to a different thing, but will not change the fact that someone who gets hold of it can try to hijack the session.
Re-generating the key on every page load should help, as it gives a limit to the time during which the key is valid.
Another thing I do is store a session variable that is an encoded string representing things php knows about the user’s environment:
md5(HASH_SALT. $_SERVER["HTTP_USER_AGENT"] . $_SERVER["REMOTE_ADDR"]);
This I can check with each new transaction to help me confirm that this is the user I think it is.
( )Timothy February 3rd
I know that a lot of people don’t implement database caching. Also, it is true that a lot of people don’t secure their sessions. And I wouldn’t just use SHA1. Learn to salt your hashes. Plus there are other (arguably better) methods of securing sessions.
( )Doug February 3rd
Thanks for this. I need to add database caching to my programs…
( )myows February 3rd
I love the pictures you chose to illustrate this article – very nice and fun touch !
( )Corey February 3rd
#1 is still not correct.
( )Now they both say ‘Hello Everyone’.
John February 3rd
Great article.
Would be great though to explain some of the protecting functions you mentioned. I don’t get more clever with you just mentioned that htmlspecialchars is an important function and should be used. Please just give a little bit of background information in the future
( )yulka February 3rd
wow! the photographs are amazing and shocking!! great addition to the article!
( )JDub February 3rd
Encrypting your session ID won’t do anything. To prevent session hijacking, use session_regenerate_id(). This changes your session id periodically, while still associating your session information to you. If for some odd reason you actually want to dissociate your session information, you can pass a Boolean true to the function.
If you’re serious about being a PHP programmer, study security. There is a certification program for this language, and you will learn a lot by studying for that too. There are far worse mistakes you can make than are in this list. If you are still making these mistakes, you are in trouble.
( )Navdeep February 3rd
Very nice article
( )Sean McArthur February 3rd
@AgentSmith – I actually no longer even understand what he was trying to say. But the code looked wrong.
To achieve the same results, you’d either do “hello $howdy”, or ‘hello ‘.$howdy
( )kevin February 3rd
@Phd Pete, “using php is a mistake”, so what do you use? are you going to say “.net”. I think so. Stop making war. People already tired of it. I am using both php and c#. It is up to the programmers. Language does not matter. Just the logic inside your head is more important. If you use other languages except PHP, you don’t make any mistakes?
( )If you are bad in one language, you will be bad in other languages as well. Don’t switch the language just because you can’t think right.
Charlie February 3rd
After all the trouble to get the right code in #1 , it turns out that the supporting evidence that is linked to doesn’t actually support the author’s claim.
It shows basically no difference in using single or double quotes from a speed perspective. If one were to pick a side based on the benchmarks there, one might actually claim that double quotes are faster.
( )Wayne February 3rd
Thanks, great article! Btw, did anyone else mention that there might be a problem with #1?
( )Kevin Martin February 3rd
Using single quotes is always best. According to many tests my peers and I have made. Double quotes take longer to process because they can also evaluate php variables within them. So:
$a = ‘hello ‘ . $who;
$b = “hello $who”;
$a would be the way to go no matter what.
( )Saeed Jabbar February 3rd
Good list. It depends on what your using single or double quotes for. If use single quotes only if you want literal strings or printing code.
( )Darren February 3rd
I agree with Charlie and Thomas that #7 does nothing. I like Charlie’s suggestion about using environment variables as an extra check for session authenticity.
( )lowell February 3rd
here’s one you missed:
11. Using PHP.
( )Matt February 3rd
To those of you saying, “Don’t use PHP”…
PHP has evolved into a very robust, scalable language. As of version 5, advanced, well-structured OOP programming is quite possible — take a look at the Zend Framework, for example. PHP has gotten a bad rap because of years of misuse and the lack of one cohesive community that focuses on best practices. But, I think its versatility and the fact that it is used by many people for many different things is actually a good thing. Clearly there’s a need to make more people aware of how to write secure, optimized code. This article had some problems but it’s a step in the right direction.
So quit with the PHP bashing… don’t blame the language, blame the programmers…
( )whiskey February 3rd
There’s one missing though… parenthesis, logic operators and you (when applied to an if statement or anywhere else).
if (!(($foo==$this) && ($bar==$that)))
if ((($foo!=$this) || ($bar!=$that)))
and such…
I know, you are smiling… Either because it hasn’t happened to you just yet, or because it already did like the rest of us (when coding past your bedtime or CUI [coding under the influence]).
( )Rebecca February 3rd
lowell!
Why oh why would you want to use anything else?
It’s the fastest, it’s easily found almost everywhere, it shouldn’t cost you a dime to set it up (software wise) and it does wonders.
What language do you use then, lowell?
( )John February 3rd
This is honestly one of the worst articles I’ve ever read. Among the applications that I support in an enterprise environment, 3 of them are PHP. 2 of them have no gain in using memcache. You don’t support any of your comments with facts or real explanation. Memcache will only help you if you’re regularly accessing the same data over and over.
To comment on your “E_ALL” suggestion, it’s not a “STRICT” mode, it simply reports ALL (note the similarity in name) errors on the page. These errors are always occurring, it’s just that warnings are generally ignored since they’re only warnings.
Two of your suggestions are simply language constructs. Not only are they avoidable by simply testing your code, but by using an IDE as well that will point out the error.
7,8, and 9 make no sense at all. Why would you store something marked as a password in your session? How does mysql_real_escape_string have any impact on simply testing cookie data, in an app that may have no impact at all on the DB much less have any dependency on mysql. I think when you say “escape entities” you mean “escape request data.”
And finally, =, ==, !=. Only two of those are comparison operators. This probably makes a third language construct issue. It should be fairly obvious to any programmer that != means Not Equals and == means equals. You make no mention of === which I find funny.
( )Brent Lee February 3rd
@lowell
( )Thanks for the super helpful tip.
j-man February 3rd
I have to agree with John and Thomas (as well as the bulk majority of other commenters)
Lots of incorrect information and conclusions here.
( )Saeed Jabbar February 4th
Matt’s evaluation is spot on especially in regards to having a unanimous community working towards improving PHP. PHP.net is a great attempt at this ,however it needs a major make over.PHP won’t be going away any time soon and as the language continues to develop it will become more standardize.Sorry for all the typos today , in a rush.
( )marxx February 4th
Thanks for this article!
I’ll bet that these are mistakes what we all have done while we were beginners!
And for all “You should do it like this..” or “that should be like this”, Maybe someone should write new article about those??
( )Well, everyone has opinion and own style to do things so..
Sagad February 4th
Are you the nettuts? Is there technical editor?. Too many mislead.
( )kevin February 4th
For those people blaming on php,
( )I saw some people had problems with php when they started learning web development, using php as their first choice.
And then they moved on to another language and as they are having more and more experience with programming idea,logic , they are getting better in web development. Then they looked back and say “php is bad” as they had hard time learning it.
I don’t mean everyone blaming php is like those people, just some of them are.
terry chay February 4th
#1 even if correct is no longer true. A lot of work has been done to get double quotes to perform nearly as fast as single quotes. I prefer single quotes myself, but if you benchmark, you’ll find no difference today between concatenation ‘hello ‘.$howdy and inline “hello $howdy”
#7 is not correct either. The session idea will unlock the sha1… variable just as well. Look up Cross Site Request Forgery and Session Fixation. You are confusing things.
The first security policy you are confusing this with using something akin to a nonce in order to prevent cross site request forgery. I’m of the opinion that using a session ID is just as good as generating something unique and storing it with the session, but many people do what you suggest and use that. Still a session ID, if hijacked is still hijacked.
Another security policy you would need is to regenerate a new session ID on successful login in order to prevent session fixation. Luckily there is a command in PHP to do just that: session_regenerate_id
The third security policy you need is that for data that is sensitive (like changing the password or purchasing a good) you have to rechallenge the user for their password (preferably behind SSL) because the session cookie has been passed back and forth during this time and is susceptible to hijacking via man in the middle.
I hope this helps and good luck at learning PHP!
Take care,
terry
( )Frank February 4th
Hehe, it seems this article is pretty much useless.
( )Susan February 4th
Setting time limits is extremely important! Thanks for pointing that out.
( )Mike February 4th
John and Terry Chay do a pretty good job pointing out the flaws in this article. If you’re trying to learn php I would forget everything you just read pretty quickly. It seems the author recycled these tidbits of knowledge from sources he did not entirely understand. I don’t mean to bash as I learned tons from my mistakes writing similar articles but a technical editor should have identified some of these flaws before making it to a site like this.
Glen Stansberry – Keep at it. If you’re interested in PHP security I would recommend APress’s book on the subject: http://www.amazon.com/Pro-PHP-Security-Chris-Snyder/dp/1590595084/
( )The parts about data filtering, session, and cookie security are extremely useful.
Haydar February 5th
Thank you, i often make a mistake in 5 and 9
5- i forget to remove E_ALL.
9- Some times i forget to escape strings, but i am reviewing and fixing almost all the websites i have worked on for security bugs.
I think every programmer must make a checklist to be checked after finishing programming, this will prevent us from making these mistakes again.
( )Nick Ferrando February 5th
Why don’t you user some scientific rigor in your articles?
( )What the f… does “mistake” mean? ERROR?? Bad Practice? BUG??
Not using memchached is not a “Mistake”, is just an option.
Bad February 5th
Newbies shouldn’t write articles.
( )Adam February 5th
This is the same guy who wrote this terrible article:
http://www.smashingmagazine.com/2008/11/18/10-advanced-php-tips-to-improve-your-progamming/
And got similar flack for it. I can’t stand his articles, and more importantly, I can’t stand that all of these big-time blogs somehow allow this guy to continue to post! ARGH
( )Arnold Lemmon Pie February 6th
yeah but ta pix are cewl!!
( )Anthony Bush February 6th
Please do not link to phpbench.com — some information there is wrong.
It would appear to be a marketing exercise more than anything, which is unfortunate because now the PHP community suffers by its misinformation.
e.g. the “Modify Loop” and “Read Loop” sections make incorrect use of the `reset()` function, which skews the results (not to mention that the results are calculated live on every page load).
WRONG: “it’s extremely good to use the reset() function in all examples” — you should NOT use reset() before a foreach loop as this is done for you and using it only slows execution.
( )João Pedro Pereira February 8th
Well, I’m very happy with my code, cause of every mistake that you talked about I’m not making any of them in my PHP code.
( )Zachary Johnson February 9th
If I had to list an 11th PHP Mistake, I would say it is using the PHP language construct empty() with string variables. You have to be careful with empty() because it returns true for the string value ‘0′. More on the quirks of empty() here:
http://www.zachstronaut.com/posts/2009/02/09/careful-with-php-empty.html
( )Clemens February 12th
I’m with Anthony Bush. I’d like to add that you shouldn’t bench PHP and report the results, since they are highly dependant on the machine they are tested with. I got extremly variegated results for the performance of different loops on different machines for example. Fast on one computer means slow on others sometimes.
This article ain’t all good. You’re basically teaching bad coding.
( )Tom Cameron February 14th
Where to start with this article?! This was.. not good. Not good at all. For a start, there is no difference whatsoever (unless it’s due to the machine) between using double and single quotes. This has been proven in past tests. It’s personal preference really.
Using htmlspecialchars() is okay, but hardly the best way to go about things. There are things that will be missed by this function; personally I’d prefer a combination of mysql_real_escape_string() and trim() to prevent these.
And finally.. database caching. Unless you have a huge site this is not going to make a huge amount of difference; reccomending it for everybody is stupid. Plain and simple.
Sorry for the negative tone of this review, but some of this article is just plain misinformation.
( )Andrew February 17th
This tut is somewhat misleading. It should be re-written.
( )Me Again April 22nd
For the life of me, I don’t understand how #7 is supposed to work. If you’re trying to prevent session hijacking you could save the IP and/or the user agent in the session and check it at every request. If you’re trying to prevent session fixation you should regenerate the session id (session_regenerate_id()) when the user logs in.
( )name 1 April 23rd
half of this advice is wrong and outright awful.
( )Henrik Bjornskov April 23rd
Isnt this a bit late for a aprils first joke article ?
( )Marcel Esser April 23rd
This article is awful. If you’re learning PHP, please don’t read this; it’s littered with misleading information, and most of it is just useless. If you really want to learn to program PHP well, go get Advanced PHP Programming by Schlossnagle.
( )Kal-El April 23rd
I think you’ve confused validation with escaping/sanitation.
htmlspecialchars, htmlentities, mysql_real_escape_string, et al. don’t validate anything. They escape/sanitize the evil characters so that you can feel somewhat safe in either inserting that data in a DB or outputting that data to the user.
Validating means making sure what you are getting back from the user is what you are expecting. e.g. – If you’re expecting an integer value, type cast it to an int, or check it with is_int, and if it fails, send it back to the user to fix.
As for #10, a good tip would not be “use the proper comparison operator”, but should rather be, “write your code in a way where, if you do mess up and use the wrong comparison operator, it will throw an error”.
What this means is, if you mean == but write = in your loop conditions (or wherever), if you put the constant value first, your code will throw an error. Here is what I mean:
while ($id = 1) // do something (except we meant $id == 1)
That bit of code will fail silently, setting $id equal to 1, and continuing on. And because it’s in a while loop, it’s always true, and you’ve gotten yourself into an infinite loop.
By reversing the sides of the equation, putting the constant first, we get the following:
while (1 = $id) // do something (except we meant 1 == $id)
This will throw an error, because you can’t set 1 equal to anything. You know immediately where the error is, and what needs to be done to fix it.
I have never confused !=, ==, or = with anything else. I may have typed them wrong (and the impetus for using the constant first method above), or got my logic wrong on occasion, meaning and writing == when I should have used !=, but I have never accidentally typed != when I meant = or ==.
( )Concerned programmer April 23rd
Oh gee… This has to be the worst PHP article I have ever read… #9 takes the cake for total “braindeadness”… htmlspecialchars will not sanitize your content in any way… At least in no way an attacker won;t know how to completely bypass…
( )Mikhail P April 23rd
#11: Writing articles about PHP without knowing WTF you’re talking about.
I think you are guilty of #11 there… It’s not really surprising you would have included it in your article, had you been aware of that particular pitfall.
( )Thibaut Allender April 23rd
This really is for beginners or wong/alarming for beginners.
SQL caching… Thank god, MySQL (the common DB companion for PHP) has some built-in caching.
Once I did a benchmark between a caching method (based on files) and a no-cache one… guess what, the no-cache was faster!
Caching DB on small or medium websites is OVERKILL.
You should begin his article with “do not overkill!”
( )Laurei April 23rd
Apart from the obvious which has been pointed out, I’ve found an interesting trend from the commenters on this post.
a.) The amount of people who don’t read blog posts but still comment.
( )b.) The amount of people who comment without actually reading, or at least skimming other comments to check that someone hasn’t just discredited the information they are commenting on, or that their comments already been said.
astho May 13th
#1 make me more confuse… hehehe…. ^^
( )michael May 14th
#10 – don’t forget === particular with functions like strpos()
( )i remember seeing a login script that allowed users to login by not specifying a password. this was easily fixed by changing the == operator to ===
wappy June 17th
#6. If yo’re using Apache it’s easier to “play” with .htaccess:
( )php_value max_execution_time 200
vidalstat June 22nd
What is the deal with all the flaming, hating on this post? Now I’ve never been accused of writing the most elegant code ever written, but I make a living–in New York City. I know, it’s a small market, not much in the way of web development, but we try. I find it hard to believe that you jerkoffs haven’t come across these sorts of mistakes in your career on a day-to-day basis.
Do you code gurus speak to your project manager that way? That’s the problem with our industry today, I wish someone like Glen would come into my office and spread a little knowledge around. Is he perfect? No. It must be nice to crank out perfect, pretty code on deadline every day of the year.
Maybe the rest of you should send in your l33t tutorials for our collective edification.
you should be ashamed of yourselves.
( )Marcel Esser June 30th
Actually, many of the people that commented to this thread have written books and articles on the topic.
No one in the above claimed that their code was perfect, or any of that other non-sense you’re accusing people of. The fact of that matter is, very simply, that a lot of the advice was wrong or misleading.
( )Mario July 12th
Of course, E_ALL is important, as long as you can track down what PHP is telling you. I’d recommend for all the new PHP programmers to check out:
http://www.phpreferencebook.com/misc/php-errors-common-mistakes/
To help decode the PHP errors.
( )Romeo October 8th
nice article… DB cache is just superb
( )Romeo October 8th
Greate Article
( )