21 ms·
2012: A Year in PHP
- h2s 14y ago> The community is always quick to learn from > its mistakes however There was a tutorials site on the front page of HN recently. It has a few PHP tutorials. http://codular.com/implementing-pagination http://codular.com/implementing-pagination $sql = 'SELECT * FROM `articles` LIMIT ' . $startArticle . ', ' . $articlesPerPage; http://codular.com/part-2-rating-system http://codular.com/part-2-rating-system INSERT INTO `ratings` (`rating`, `ip`) VALUES ('{$rating}', '{$_SERVER['REMOTE_ADDR']}') In fairness these aren't your typical "straight out of $_GET" vulnerabilities, but they impart a lax attitude towards security. For example, in the latter example above, $rating is escaped just prior to its use in that query, but $_SERVER['REMOTE_ADDR'] isn't. In the former, there is no indication whatsoever of where the variable $articlesPerPage has come from so it's impossible to tell. The notion that some variables are "safe enough" that they don't need escaping is naive. $_SERVER['REMOTE_ADDR'] is a global variable that any other code anywhere in the script can write to. While you can't get owned immediately after putting that code live, it is still a tiny little SQL injection vulnerability waiting behind the scenes for an attacker to chain it together with some other similarly minor flaw and break in. To this day I still come across PHP code that is vulnerable to serious, immediate SQL injection vulnerabilities and it isn't always old code. I'm not so sure that the PHP community is so quick in learning from its mistakes.
- RobAley 14y ago> To this day I still come across PHP code that is vulnerable to serious, immediate SQL injection vulnerabilities and it isn't always old code. I'm not so sure that the PHP community is so quick in learning from its mistakes. Do you not find that with other languages as well? I do.
- Daishiman 14y agoI don't know of any single, relevant Ruby or Python tutorial that does not insist on the importance of using a DB API for secure insertion of data.
- simonw 14y agoIt's a bit harsh judging the entire PHP community by the presence of yet another crap tutorial on the internet. You can bet that the people who go to PHP conferences etc (and who comprise the core PHP "community") wouldn't write example code like that.
- jeltz 14y agoAll programming languages have their share of terrible tutorials, but of all languages I have used PHP has the by far worst tutorials. The PHP core community might not write such tutorials but there are loads of people who do.
- h2s 14y agoSorry about this grumbling old man comment. I was bored and tired and I was meaning to delete it, but it has replies and stuff now so it seems a bit too sneaky. Something about HN brings out the angry jerk in me sometimes. My bad, though.
- pestaa 14y agoNo need to apologize at all. Combined with your inner grumbling old man there are still not enough hackers bashing the stupid faulty practices PHP encourages. Edit: "encourage" as in (a) not discouraging and (b) making them easier to use for novices (without understanding the consequences).
- bpatrianakos 14y agoYour comment doesn't seem "in fairness" at all. Can you tell me which language is impervious to SQL vulnerabilities? Is there some magic language out there that cleans all external input for you? Pick a language, any language, and you will just about always find that GET and POST variables aren't cleaned for you and rightly so! The language should be a tool to let you do whatever you want and leave it up to the programmer to clean input. Now, if you want to talk about frameworks that's a different story. You picked one site with one tutorial and based off that have basically proclaimed PHP to be an insecure language. For every tutorial that skips over security or has some mistake or vulnerability there are others out there that don't. The one you chose is in PHP but you can find tutorials in any language with the same flaws. We all get it by now. PHP is lame and it's cool to bash it. It has a history of being crappy. Fine, we know. But PHP in past couple of years has begun to address those flaws and has come a long way. Now that it's starting to get better people seem to want to cheer for it to fail. No matter how uncool it is it's still incredibly popular even among people here on HN. It's just that they don't like to talk about it out loud because of the stigma it now has among the language snobs. I mean, come on man. Was this really in fairness or just another cheap and easy shot. An opportunity to pile on. And to address the quote you mention... the web may still have a lot of those old and awful tutorials but that doesn't mean the community hasn't learned. More recent tutorials and information you find online is much better and the community is far more cognizant of PHPs vulnerabilities and are now using best practices far more frequently. It's always fun to bash PHP but let's just give credit where credit is due. It has taken enough steps in the right direction for it to be worthy of people taking notice. EDIT: Also, the tutorial site you linked to is actually quite good. Tutorials are tutorials, not technical manuals. So when you want to show someone how to, for example, take GET or POST input and manipulate it somehow you want to focus on that and not explain every little thing like all the ways your GET or POST array can kill you via XSS or SQL injection. You might mention in passing that you'd better clean your input but unless the article is about sanitizing and escaping inputs itself I don't see why it has an obligation to go into that much depth.
- pavel_lishin 14y ago> Can you tell me which language is impervious to SQL vulnerabilities? That's not the point. The point is that PHP tutorials/books/best practice guidelines repeatedly and consistently do this sort of thing. Even "PHP: The Good Parts" spent most of the chapter on SQL without mentioning security until the very last part, where they sort of waved their hands at it.
- jamescun 14y agoJudging the whole of PHP and its community on the basis of one very poor tutorial is very unfair to PHP and its community. There is a lot of good PHP code out there and successful applications which don't/rarely suffer these kind of exploits (at least no more so than other apps written in other languages). I'm fairly sure crap tutorials and SQL injections are possible in every language.
- tangue 14y agoPart of this problem is that a good part of the community is amateur/hobbyist, they won't learn anything. Some people in the PHP community love to think that PHP is used like Java, but for most of the amateurs it's a "cut and paste what works" workflow.
- rorrr 14y agoThese specific examples actually don't contain vulnerabilities. $startArticle is guaranteed to be an integer, for example. Blaming some badly written tutorials on the language is just trollish-lame.
- dkhenry 14y agoWhats missing from this list? HipHop making an alternative VM. I see that as the biggest change in PHP in 2012. Sure HipHop has a translator/compiler (HPHPc) for a while now, but now they have a full fledged VM with a JIT (HHVM). Maybe next year we can get a sane extension framework and make a less memory intensive construct then zvals.
- ihsw 14y agoThere are some alternative data constructs in PHP, for example there are the SplFixedArray[1] and SplDoublyLinkedList[2] classes. The SPL data structures are meant to be faster and leaner implementations of common data structures that are usually created ad hoc in plain PHP. [1] http://ca.php.net/splfixedarray http://ca.php.net/splfixedarray [2] http://ca.php.net/manual/en/class.spldoublylinkedlist.php http://ca.php.net/manual/en/class.spldoublylinkedlist.php
- mgkimsal 14y agoSplFixedArray tends to use about 30% less memory overalll, based on some tests I did about a year ago with PHP 5.3
- dkhenry 14y agoThose are good and help a little, but the real issue isn't just the zval containers its zvals themselves. the Spl* structures are just proof that there is lots of room for improvement of the raw php data types.
- mjs 14y agoHipHop is incredibly promising, though it basically wasn't used outside Facebook in 2012. I hope it will get more adoption in 2013, which (as well as the performance benefits) should make PHP play a bit better with the Heroku-style services. (Since it makes a full-on web server unnecessary.)
- thelarry 14y agoI heard with hip hop you cannot easily use your typical C php plugins?
- dangerlibrary 14y ago> PHP5.4, PHP5.5, PHP5.2 and PHP5.3 (in that order...) I thought Python limping from 2.7 to 3.3 was silly and confusing. I'm glad I haven't been working in a PHP shop recently.
- k3n 14y agoIt's not that bad, really. Most people are using 5.3 and are either moving towards 5.4 or recently moved to 5.4. Those on 5.2 are probably stuck there for reasons outside of their control. And 5.5 hasn't even been released, so you can completely ignore it for the most part.
- Joeri 14y agoWhat still bothers me about PHP is the split personality between the old parts (global functions, bad defaults), and the newer OO parts. I want a proper string object that is natively unicode. I want methods on my primitives like in javascript. I've done some experimenting with meta-programming that into PHP, but it should really be done at the language level. (For anyone interested, this is my experiment: https://github.com/jsebrech/php-o https://github.com/jsebrech/php-o )
- lhnz 14y agoI agree with you and I always wondered why the internals team hadn't done this themselves and just left the original functions as warty aliases for backwards compatibility.
- kodablah 14y agoI too have been doing some work with meta-programming in PHP (specifically working on a typed language that cross-compiles). PHP isn't completely object oriented...even new functions for password stuff in 5.5 are added as stateless global functions w/ params. At this point, it's not worth it to change the language significantly...everyone knows the mistakes made and they just move on. As for your project, it's neat. Runtime parsing and handling of docblock annotations can be a tad heavy and cumbersome. Some kind of pre-compiler might be nice. Also, toss your stuff on composer/packagist and you might find https://github.com/phpDocumentor/ReflectionDocBlock https://github.com/phpDocumentor/ReflectionDocBlock helpful too.
- Joeri 14y agoI disagree that we should just accept that PHP's old parts are a mess and never revisit them. The date functions were revisited when the DateTime type was introduced. Nothing prevents the introduction of String and Array types. The legacy string and array API's are a mess, and they affect productivity and code quality.
- pan69 14y agoIn the way you explain it, PHP isn't that different from C++. In C++ you can ignore all OO concepts and simply write C style procedural programs as well. No one mentions this when they discuss C++. I don't see why this "split personality" should be a problem with PHP. It's simply a language evolving, just like C did when C++ came around by keeping the old stuff around and adding new features.
- vojant 14y agoPHP is getting better and better. I really love this language.
- xxiao 14y agolove PHP!
- virtualwhys 14y agoPHP is getting traits? The next thing you know PHP will be type safe and scale, heh, heh ;-) Seriously, Wordpress with a custom theme is a nice way to slap some bling on the front end and provide clients with an excellent CMS, but otherwise, for custom functionality, PHP? Thanks, I'll pass.
- eitland 14y agoNow you are either misinformed or trying to get away with unwarranted PHP bashing. PHP scales well. Rest assured, plenty real annoyances with php :-)
- pestaa 14y ago> PHP scales well. Any backend will scale if it runs in parallel and you throw enough hardware at it. Perhaps a more important question would be whether PHP scales codebase-wise in larger projects.
- maratd 14y ago> Perhaps a more important question would be whether PHP scales codebase-wise in larger projects. Yes, it does. From my experience and apparently, that of Facebook.
- beering 14y agoFacebook is maybe not the best example. Remember, they did end up writing about 3 different implementations of PHP because of their scale. If anything, their case shows that they threw enough money at it to make it work.
- maratd 14y ago> they did end up writing about 3 different implementations of PHP because of their scale. And each of those implementations is PHP. It is open source and is available to the public. I am working on integrating it into my stack. > If anything, their case shows that they threw enough money at it to make it work. I thank them for their money and will now apply their hard earned work. What other language has that kind of commitment behind it?
- mootothemax 14y agoPHP definitely has its annoyances: the function naming scheme alone still drives me mad after nearly 15 years of PHP experience. That said though, like most IT projects, the more you put in at the start, the more you get out in the end. If you rush into a project and don't plan out even the basics, it only stands to reason that you'll end up in a mess. Along these lines, I have to wonder how many problems the quick-fix tutorial-style articles cost after developers copy-and-paste in an attempt to hurry through a project. My guess: lots. Personally, I think it's an exciting time to be in PHP. It's possible to put together complicated, scalable sites in what is really an incredibly short amount of time.
- Mahn 14y agoI hate how to this day PHP still lacks of an obvious way to write object literals, instead forcing you to either cast arrays, which is verbose and ugly, or use stdClasses, which personally I do but damn are they a pain to use and maintaining for nested structures. This reason alone is what would make me switch to nodejs next time I start something.
- yogo 14y agoThere has been support for object literals for quite some time now (https://wiki.php.net/rfc/objectarrayliterals https://wiki.php.net/rfc/objectarrayliterals) but maybe just not enough. It would definitely be a welcome addition to the language. At least we no longer need to write array() for arrays lol.
- Mahn 14y agoOnly array literals were implemented though, not objects. That was long overdue, but in the age of JSON we live in it's not enough. For instance, the following in Javascript: var myObject = { memberOne: 'some string value', memberTwo: { subMemberOne: 42, subMemberTwo: 48 }, memberThree: false }; Has this as the closest equivalent in PHP right now: $myObject = (object) [ "memberOne" => 'some string value', "memberTwo" => (object) [ "subMemberOne": 42, "subMemberTwo": 48 ], "memberThree" => false ]; It's verbose, really, I would very much prefer a native solution that doesn't enforce casting from array and quotation around property names.
- yogo 14y agoI know, note what I said "...maybe just not enough. It would definitely be a welcome addition to the language" People have proposed it and commented on it but it does not get enough support (votes) from senior devs to get included. Maybe with more requests it will get included finally.
- joshstrange 14y agoI'm surprised there was no mention of http://Laravel.com http://Laravel.com
- mjs 14y agoI don't really get Laravel. The docs talk about dependency injection but at the same time they really really love static function calls. For example there's no event manager class, only a single, global event manager: e.g. "Event::fire('loaded')". What if I want to use a different event manager? (To pass event calls across the network, for example.) There doesn't seem to be any way to do this, and pretty much all the core classes are like this. http://laravel.com/docs/events http://laravel.com/docs/events
- nyam 14y agoyesss, laravel is the most promising of all. few weeks ago, i wanted to make small site in php, i evaluated nette (poor docs, bugs), silex (couldn't get autoloading to work on shared host) and finaly laravel - by far best! especialy eloquent orm is simple yet very usable AR impl, all api's very simple and clean - this fw has very railsy feeling overall. there is laravel 4 behind the doors, i was playing little bit with it, it's even better (copy of rails :-)) - autor claims full DI support so testing should be simple... L4 https://github.com/illuminate/app https://github.com/illuminate/app
- embplat 14y agoIndeed. Laravel (especially the upcoming version 4) is the best thing that happened to the PHP community in a while!
- krapp 14y agoLaravel is my first experience with php frameworks. I have yet to actually finish a project in it which is disappointing (for something whose entire purpose is to make finishing projects faster) but I really like it. It's been a huge educational experience for me.
- overgun77 14y agoNot trying to undermine your skills, but if you can't get something done, it's not the tool's fault.
- AlexMuir 14y agoCan anyone point me to what would be regarded as a best-practice PHP codebase? Ideally something that's testable. I used to do all my work in PHP but moved to Rails and adopted TDD/BDD. I'm just not sure how this would fit back in to the PHP world.
- eitland 14y ago4 of years ago I liked symfony. Haven't really tested it in a while though but later versions look like improvements in everything but learning curve. But I'd say the same goes for rails.
- porker 14y ago@AlexMuir I second this - Symfony2 has made huge strides forward for BDD. Here's an article that might help: http://docs.behat.org/cookbook/bdd_in_symfony2_with_behat_mink_and_zombiejs.html http://docs.behat.org/cookbook/bdd_in_symfony2_with_behat_mi...
- ZeroGravitas 14y agoThirded. I came up to speed with PHP recently and spent a lot of time searching for "best practices" or other variations of that keyword to see what I could build on. The stuff I found was generally quite frighteningly bad, mostly people getting excited about the most absurd micro-"optimisations" (and that's after explicitly discounting anything more than a few years old). But the ecosystem around symfony 2 seems to be where all the sane (imho) PHP developers are heading. In particular they seem to have drawn a line under old versions of PHP and made good use of the newer features added to the language to build modular components. For a while I wondered whether everyone who wanted to use these techniques had all been driven out into the arms of Ruby (on Rails) and Python. But the Symfony guys seem to have just re-imported a lot of the best ideas back into PHP from projects like Rack, Sinatra, Django, Rails, Cucumber etc.
- kayoone 14y agoCheck out the symfony framework version 2.1+ Its the best way to write PHP applications today and i am pretty sure its ahead of the web frameworks in most other popular languages.
- contingencies 14y ago14 years of PHP here. My year in PHP was spent counteracting godawful newbie PHP developers' idea of what is 'best practice'. "Framework convergence"? "A common autoloading strategy"? Come on. Perhaps 85% of PHP (we could almost say web) projects are fire-and-forget, with minimal maintenance. No, I don't have sources, but yes, you know it's true. This is the web programming world's dirty-little secret. Same goes for RoR, and the rest of them. What does this mean? The code produced simply doesn't matter. Bitrot is accepted. Nobody cares. Of course, then there are maintained projects, complex infrastructures, things that push the boundaries. But they are so few and far between that their lessons are difficult to generalize, certainly with any significant bearing on PHP as a language as opposed to general programming practice. Meanwhile, people scream from the lamp-posts about 'best practice'. For example, I was informed by an inexperienced developer a couple of years ago that it was now considered (by who?) 'best practice' to leave out the closing tags in PHP files. WTF? More muck - let's look at the article's topic of 'autoloading'. Symptom: annoying code to type all over the place, thinks developer: "my HairyStinkySpittingCamelCaseClass extends GeneralObjectOrientedAnimalIrritantClass". Oops, need to also type in 'require_once('classes/irritants/animals/objectoriented/general.inc');' up there. Oh no, now I'm getting lazy. Oh but this framework has this autoloader thing! I should use that. That's what someone else did! How cool is that!" Wrong. You are incrementally introducing complexity, tight-coupling, and turning your execution flow in to spaghetti. Probable cause: Extreme overuse of the OO model, generally. Obvious fix: Stop (over)using OO. Yes, you heard me right. Stop using OO. Just try it. Code immediately becomes so much more concise, readable, and re-usable. (Oh, for the days of PHP3! Hahah.) I challenge you or your team to refactor some part of your codebase in to non-OO and see if it doesn't improve. Of course, if you are really new then your whole codebase is linked to your framework's inherent model (probably some MVC thing that only partially functions architecturally) and you won't be able to figure out where to start with such a task. But do try, it will be interesting, I guarantee it. I'm not saying OO is useless, just that most times it's used in PHP code it's contributing nothing useful and would be better having been left out. Look hard and I would be surprised if you don't concur. So yes, for me, 2012 was mostly a year like any other in PHP. Ignoring vocal people while getting things done. Still amazed at how broken the whole pear thing is. And PHPUnit, hah. That thing is so PHP4+ Javafied best-practice Germanic, it should be in a modern art gallery. (And I say that as a nominal German.) Anyway, 14 years and PHP is still the most bulletproof language for getting stuff done on the web. So dear PHP authors, thanks for saving us from perl/cgi (though perl has it's place, it's not the best tool for the web). You deserve a medal. Particularly for early and reliable UTF8 support, which gave me a fine excuse not to switch to ruby 5+ years ago, even though I really, really wanted to, and still prefer its syntax and features. However, your OO implementation was crap, and your function naming and parameter ordering is impenetrably wacky, even after a decade and a half. But that's OK, nobody's perfect. We still love you :) Happy new year, PHP community.
- M4N14C 14y agoIs it mandatory to format all PHP code as poorly as possible?
- wolfpackk 14y agoHow accurate are http://w3techs.com http://w3techs.com stats? They seem to be missing many server side statistics, are they just checking the url for an extension?
- tiwazz 14y agoAm I the only one that finds these deeply nested namespaces completely unusable? https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php#L14 https://github.com/symfony/symfony/blob/master/src/Symfony/B... I thought the point of autoloading was to make things easier, not to replace require_once with something more verbose. Why should I have to import classes from within my own package?
- nachteilig 14y agoI don't find it _completely_ unusable, but I'll admit that it's pretty frustrating.
- contingencies 14y agoYou're not alone. It's a symptom of people trying to solve everything with one toolset ("Me know hammer, me use hammer!"). In practice, most OO projects regardless of language have classes like 'LatestThingOtherThingIKindaRememberSomethingSomeoneElseWroteDontTouchIt', combined with a non-negotiable and often intrinsically (looking directly at any given piece of code) inexplicit set of dependency assumptions around the global object model. In general we need less OO, and more immediately apparent, procedural, loosely coupled code. Programs that "do one thing and do it well".
- stephenr 14y agoJust because symfony has fucked naming and use of namespaces doesn't mean namespaces are bad.
- methodin 14y agoPeople seem to forget that enterprisey code is drastically different from your own small projects. Having even composer in multi-person dev teams that have niche understandings can drastically improve code quality because it tends to lend itself to componentized architecture. This alone will help you escape the typical procedural nightmares if you are so inclined to do so. PEAR was crap and lent itself to crap code. Composer is the opposite and it shows. Github and composer really should be the winners of PHP 2012 (aside from the advancements in PHP itself) as they alone have transformed the landscape in very tangible ways. I'd give props to Symfony too as they have forced most other frameworks to begin thinking outside the monolithic framework mindset. Then again I suppose it's a little naive to expect people to escape their bubble of understanding, but I can keep on hoping.