106 points · by h2s · 13y ago · 146 comments
> 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
$sql = 'SELECT * FROM `articles` LIMIT ' . $startArticle . ', ' . $articlesPerPage;
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.
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.
I do disagree with you on some of your points about tutorials though. You claim it's possible to find such insecure example code for any language, and that's probably true. But is it easy? The first search result for "python mysql tutorial" [1] doesn't contain any SQL injection vulnerabilities. Neither does the first result for "ruby mysql tutorial" [2]. All seems well with "java mysql tutorial" [3] too. Surely the first Google result for "php mysql tutorial" [4] can't be that bad then?
$first=$_POST['first'];
$last=$_POST['last'];
$phone=$_POST['phone'];
$mobile=$_POST['mobile'];
$fax=$_POST['fax'];
$email=$_POST['email'];
$web=$_POST['web'];
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO contacts VALUES ('','$first','$last','$phone','$mobile','$fax','$email','$web')";
mysql_query($query);
Ouch. In this case, your point about this being an "old and awful" tutorial does apply. But the tutorials from my original post are new, as in "2013" new. And they were on the front page of HN not one week ago. It's like, finally here comes a fresh-looking new site that looks like it might even have a shot at knocking that garbage from "freewebmasterhelp.com" off the top spot on Google, and it's still not as good as it should be.[1] http://zetcode.com/databases/mysqlpythontutorial/
[2] http://zetcode.com/db/mysqlrubytutorial/
However, PHP is no longer a templating language. It's a full featured programming language that is used to build a variety of different systems. Trained developers work with PHP every day to build solid, testable and secure code.
There is no excuse for any trained developer to write code like that. Perhaps you shouldn't judge the language just because some untrained idiot put up a bad tutorial.
I do agree that the above example is the rule rather than the exception as most books I've owned show something similar or worse:
foreach($_POST as $key => $value) { ${$key} = $value; }
That's almost as convenient as that magic global form garbage they used to have turned on by default.
I was under the impression though that the MySQLi adapter and PDO both made use of prepared statements. All we need to do now, is clean up the last few years of cruft/misinformation still floating around.
But anyway I think we might just view tutorials differently. To me, what's posted above is an outdated, insecure way to put data into a database but it definitely answers the question "how do I put stuff in a databse" simply and right to the point. And that's what I like about PHP tutorials. I'd rather put the onus on the programmer to learn how to put "way to do X' and "way to do Y" together on their own rather than muddy the waters with "here's how to do X but this is important too so let's show you how to do this other thing at the same time".
Python, Ruby, Perl, Java and even C# all have popular, widely used SQL interface libraries where placeholders are the norm. Only PHP even considers injecting user data into queries. This is extremely harmful.
Tutorials should show best practices, not just the first thing that works. There should be significant attention paid to how to construct a safe and reliable query. This is not a secondary concern, not when there are automatic hacking tools with a very scary list of features (http://sqlmap.org/) out there for anyone to download.
Microsoft used to be very hand-wavey about security issues and it cost them severely. Now they've tightened all the bolts and Windows is in much better shape because of it.
The PHP community needs to root out these poisonously bad tutorials and eliminate them from search results. How can this be done? By making better tutorials and linking to them more aggressively.
Stop pretending this isn't a problem and start fixing it.
Forcing cheapo web hosts to enable mysqli or PDO will hopefully help a great deal.
I just think they should have added E_DEPRECATED warnings in 5.4 - but I see why they didn't.
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.
You can shoot yourself in the foot with any programming language. PHP just happens to have one of the shallowest learning curves and greatest availability, so simply by virtue of being everywhere it's responsible for a lot of damage. It doesn't help that a newbie that came up with a working (but dangerous/incorrect/...) solution can then easily start answering other newbies' questions, although that's hardly a PHP-specific thing.
Further - because it's so many people's first programming language, they don't even know to look for information about best practices, let alone go out of their way for it. It takes a seasoned programmer to go out of his/her way to avoid repeating other people's mistakes.
In the edit to my comment above I touched on this. In short, when you instruct someone on how to do something you put the focus on the task and not the peripheral stuff. You may mention it in passing but to explicitly go over certain things may not be the right thing to do. I can totally see any book or tutorial showing people how to do certain things without mentioning security or kind of glossing over them. That's because you want to make sure a person gets the concept first. Once a person gets how to work with GET/POST or do anything else for that matter, you can then explicitly go over security, mention where to look for vulnerabilities, where to use the security techniques etc.
I learned a touch of Ruby and I'm getting decent with Python right now and pretty much everything I've read either completely skipped security or mentioned it in passing. At a certain point security is introduced and by that point I understood the language enough to know where to apply it in the previous examples from whatever I read. I've also been reading a copy of "Javascript: The Good Parts" and it does much the same thing where you get comfortable with the concepts and security comes later.
I think that because of PHPs history of security problems people are extra sensitive to any PHP code they read online and are almost looking for any way to jump up and say "that's not secure!!". PHP deserves that because of how it used to be but things have and are still changing very much.
If by "magic" you mean simply disallowing non-structured queries (which is pretty darn easy with a Structured Query Language):
http://en.wikipedia.org/wiki/Language_Integrated_Query
http://www.impredicative.com/ur/
http://pgocaml.forge.ocamlcore.org/
https://github.com/mfp/ocaml-sqlexpr
and that's just off the top of my head.
DB["insert into foo (bar, baz, qux) VALUES (?, ?, ?)", bar, baz, qux].insert
And the library handles all the escaping, and even type conversion for you (e.g. Date objects to SQL compatible date strings)
Edit: "encourage" as in (a) not discouraging and (b) making them easier to use for novices (without understanding the consequences).
Do you not find that with other languages as well? I do.
The PHP core community might not write such tutorials but there are loads of people who do.
I'm fairly sure crap tutorials and SQL injections are possible in every language.
Blaming some badly written tutorials on the language is just trollish-lame.
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.
If a VM makes them design sane consistent and useable versions of those plugins from the ground up PHP may be improved as a result.
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
[2] http://ca.php.net/manual/en/class.spldoublylinkedlist.php
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 )
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 helpful too.
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.
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.
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?
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".
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.
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.
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.
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.
Rest assured, plenty real annoyances with php :-)
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.
Note to self: research (non-existent) parallel processing in (single threaded) PHP; also, find enough hardware to make PHP scale ;-)
Yes, it does. From my experience and apparently, that of Facebook.
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.
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.
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.
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.
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.
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.
With this statement, I can't decide if you are being serious or just having a good laugh.
> Perhaps 85% of PHP (we could almost say web) projects are fire-and-forget, with minimal maintenance.
Keep in mind, your knowledge is based on your environment. If you work with bad code, that's all you know. I don't, so I don't realize what it's like working "in the wild."
As for the "I don't work with bad code because I wrote it myself or in this particular small environment" comment, that's great. I have worked in many countries, so I have a fairly broad experience, and IMHO much of the webcode industry to be pretty fire-and-forget vs. other areas of programming.
But... I'm inclined to agree with you about OO. It's far over used by developers who don't have the experience to know when to stop. Dependancy Injection? God damn, are we actually solving problems or covering up issues with a programming paradigm? This solves a problem I never knew I had...
Traits and "mix ins" blow my mind. How bout just using a bloody function call in a library (yes, these can be testable just fine too without the word "class" in there).
Maybe I've just head my head neck deep in functional/procedural code for too long to appreciate things, but none of my OO systems has ever achieved the need for overly complicated management systems like DI or traits.
As for your argument against traits, using global functions clutters up the global namespace and doesn't lend very well to modular development. Next thing you know you have two libraries with "create_hash($string)" or something similar that do two different things.
*Edit: clarification
I think if you are working at a scale where this is even ridiculously relevant then you will prefer to manually specify required libraries and maintain a closer understanding of control flow at all times.
If not, then you would at least start measuring performance characteristics. When you do that, you will find that if you are pre-loading these things on your last query they will just live in OS filesystem cache (ie. already in memory). (Note: If your load time is disk-affected, a half decent sysadmin could just hard cache your code in memory anyway...)
Sure, you will have slightly longer interpreting time (again, not likely to matter, except at huge scale), but that will be offset by things like: (1) Any number of potential caching layers - OS filesystem, APC, etc. - which should maintain these cached either in memory or both in memory as PHP bytecode, thus largely effacing this concern (2) enhanced simplicity for everyone.
While I'm all for low-hanging performance fruit, this particular approach ('autoload') costs too much and delivers too little to be generally praiseworthy, whilst harming simplcity. It's justifying itself as optimization, and on many levels it just isn't. It's going backwards.
Most misunderstood quote of programming. Premature is the qualifier.
Edit: After reading the rest of your comment I don't think you really learned or experienced much over 14 years. It also goes to show how misleading experience in number of years can be.
What is the effect of the additional text in the file with the closing tag? They are output, and visible.
What is the effect of the additional text in the file without the closing tag? It is interpreted as code, becoming a potential security issue.
Are they difficult to track down because your development process sucks, or because there's something illogical and mystical going on? (Hint: There's nothing illogical and mystical going on)
Using continuous integration (an RCS/VCS-linked automated testing scheme) you can trivially determine which change broke which part of a system. In fact, you don't have to, because the system will tell you.
If you are worried specifically about accidental newlines at the end of a file, you can just write a rule in ~project/.git/hooks/pre-commit (or similar on a server) that rejects checkins that don't match that style.
Going around telling the whole world to adopt some ridiculous habit because your development process is out of the stone age is a reflection on that process only.
Protip: You exclude closing ?> tags from your files because if there's a new line after them, you'll get the headers already sent error, which is a big headache to track down.
Or you could just leave off the closing tags that serve no purpose?
It's not acceptable having to import a monolithic framework to write a simple webapp. All webapps start simple...
It's not acceptable having MVC crammed down my throat, when MVC, which fits desktop development perfectly, feels shoehorned in webapp environments.
So many frameworks have great code in there only to be unusable because it's trapped in monolithic OO monsters. I'm looking at you Zend, or Cake, or even symphony...
That being said, nicer frameworks are appearing. Aura and Fuel both look great.
Thanks, much appreciated.
It's a real bug-bear of mine that, in the profession as a whole, this attitude is rarely criticised, and sometimes even praised (especially on HN with the JUST SHIP IT startup mentality).
A lot of people are fine with this and can probably offer a lot of reasons pertaining to business interests, which is fine. Those can be measured, deliberate compromises backed by sound reasoning and opportunity cost. But there's this other school of thought that just thinks, "fuck it, it's just code innit."
And it seems that newcomers to programming (in PHP/on the web) are still being taught at that school.
My point in mentioning this (little discussed, IMHO) property of web development in general was that many people's experience in PHP is limited to such projects, and therefore their notional understanding of software design from a maintenance perspective is limited; most of the community are not experienced programmers. IMHO this limit has been further amplified by a reliance on frameworks which are themselves often based upon fairly questionable design decisions, and are blindly worshipped as some kind of gospel.
Let's also hope that no noobs that were doing, or trying to do, the right thing (formal company coding practice aside) were negatively impacted in the process through performance reviews, perception, compensation, or otherwise. We understand that best practices are subjective to a degree, and that features of any language or platform will be abused. I also take this opportunity to encourage the PHP developers to add features that they believe solve real world problems and continue to make life easier for other developers.
slams gavel
Thank you for watching Coding Court lmao
Why on earth are you, the guy preaching simplicity, advocating for including absolutely useless, unneeded code at the end of every file?
How does that reconcile?
What do you mean by that? It has a rather simple concept of strings and a very interesting set of mb_... functions as far as I remember. PHP strings are just bytes and are not even encoding-aware themselves.
In hindsight I think having this just work for a lot of people is where PHP trumped perl and ruby in a way.