views:

311

answers:

8

Hello, I have been learning php, by just plugging away at it.

I was hoping someone could point me in the right direction in regards to security, flow and general best practices?

Thanks.

+6  A: 

Use a freely available framework such as:

  • Zend Framework
  • CakePHP
  • CodeIgniter (See comments)
  • Kohana (From @Alex's answer)

and follow the standards specified by that framework.

Billy ONeal
Don't look at CI unless you want to know how to code in PHP4 again :P
alex
@alex: I'm trying to not write a subjective answer by just listing frameworks. Listing a *single* framework invites flame wars.
Billy ONeal
@Billy ONeal Sure, just sayin'
alex
@Alex: I did put a note there stating to read your comment...
Billy ONeal
@Billy ONeal We did a answer shout out exchange :D
alex
@alex Whats "CI"
TechplexEngineer
@TechplexEngineer CodeIgniter
alex
@TechplexEngineer: "CodeIgniter". And I really want to smash the downvoter for not commenting.
Billy ONeal
I looked at the zend framework but it seemed wayy to complex for the simple app i'm developing
TechplexEngineer
@TechplexEngineer: That's why I mentioned several frameworks. PHP's biggest problem is that **by default** it mixes implementation with the interface of the web page. Any framework's first job is breaking those concerns apart. Which specific framework is less important than using some form of framework.
Billy ONeal
@Billy: +1 for your answer, and +1 for your comment above mine: that's so true.
Cam
-1 for suggesting you can learn to write better code by using other peoples code instead.
symcbean
@symcbean: Why is that an invalid suggestion? [Good programmers never design what they can steal](http://www.codinghorror.com/blog/2004/12/never-design-what-you-can-steal.html).
Billy ONeal
@Lotus: When I disagree with something, I'm going to leave a comment. I fail to see how that is trolling. I'm not going to censor ideas simply because they are unpopular.
Billy ONeal
@Lotus: What specifically have I said that "added nothing to the discussion" and "flooded the question with tons of irrelevant arguing"? Has a single comment I have left not been a direct response to something that has been in the person's answer? For a single person who made changes to their answer as a result of the comment, is there a single freaking answer where I did not upvote thank the poster directly in a comment? How is that being a troll?
Billy ONeal
+5  A: 

Take a look at a reputable open source software, that is known for good code.

Look at Kohana's source, or any of the others from Billy ONeal's answer.

I wouldn't recommend using CI's source as a guide - as I think it still supports PHP4, so some of the code will be useless to learn - unless you plan on writing PHP4 code, which is a bad idea if you are only learning now.

Do not look at WordPress, you will pick up some terrible habits.

Also, while I think of it, learn about OO, and the difference with procedural code.

alex
+1. You mean, more terrible than PHP is by itself? *Bill shudders*
Billy ONeal
How about Drupal's code?
TechplexEngineer
@TechplexEngineer: Depends. Current shipping versions of Drupal are still a ton of PHP4. I believe their skunk-works version is PHP5 all the way though.
Billy ONeal
@TechplexEngineer Drupal doesn't use OO much I don't think - they say that PHP doesn't support it well (I disagree). They say they use the [concepts](http://drupal.org/node/547518).
alex
There are only minor semantic differences between PHP4 and PHP5. It's worrisome to praise syntactic salt as end in itself. Sounds like encouraging premeditated incompatibility without use case.
mario
@mario: Have you actually written code in both languages? Their object models are completely different! (And 4 is no longer being supported)
Billy ONeal
@mario *You* can keep coding with PHP4 then...
alex
Yes I'm using PHP since v3. And apart from the inherent references in PHP5 the object models are identical. There are new toys like interfaces and access modifiers, but toys they are.
mario
Yes, new toys like **<insert most everything required to be an object oriented language here>**.
Billy ONeal
Aw, who removed their upvote? :(
alex
@alex: Not me :(
Billy ONeal
+1 for "Do not look at WordPress..."
W_P
Let's see. Python has no access modifiers or interfaces. It supports multiple inheritance instead. By all measurements it's a proper object-oriented language, whereas PHP can't even treat functions or atomic values as objects. PHP developers copied some features from Java, but that doesn't turn it magically into an object-oriented language. PHP5 is not much better than PHP4 in that regard. Glorifying them as different languages is enterely ludicrous.
mario
@mario: Okay, so Python does things differently. But it still provides some way to achieve the same things. PHP4 provides no such facility. PHP4's classes are little different from a `struct` in C, yet nobody is coming out here and trying to say C is an object oriented language. I'm not saying that object orientation is the one true solution to everything, but if you're advertising a feature of your language, then you should at least do that feature correctly. (Side note: I don't think Python would be the best example of an OO language either. It's a great scripting language though...)
Billy ONeal
Well, actually. The gtk/glib guys are using C as an object-oriented language. I've once written some Assembler to interface with Turbo Pascal objects. So to me it's shallow differences. And I fail to see an inherent difference between v4 and PHP5. I admit most of my object structures wouldn't work with PHP4 anymore, because I make extensive use of SPL, ArrayAccess and Co. However there is no point in incompatibilizing it without use case, and "code in PHP5" isn't a very sensical statement. It's the same language, no world changer.
mario
@mario: You can write object oriented code in most any language (the prime exception I am aware of are most dialects of Lisp/pure functional languages). But a language which claims to directly support that paradigm needs to do some work to actually support that paradigm. C doesn't, therefore C is not an OO language. That doesn't mean that you can't write OO code there, it just means that the language doesn't help you.
Billy ONeal
Yes, so OO languages come in varying flavours. But why is everybody so adamant that PHP5 is "more" object-oriented or a new language? The new stuff it brought aren't dependencies for OOP.
mario
@mario Well I'd say PHP5 has better support for OO and its paradigms. PHP4 had *basic* support for objects.
alex
I can agree to that definition. I only take offense to recommending syntax constructs when there isn't a functional purpose.
mario
It is possible to do some seriously good OO programming in PHP4. But it is noticeably easier in PHP5. I've built quite powerful ORMs in both.
staticsan
Indeed. Structurally you can achieve the same. But specific tools like ORMs can become more useful with enhanced PHP5 constructs like Iterators and ArrayAccess.
mario
+10  A: 

Good programming is irrelevant of language. I suggest you start studying software development concepts such as object oriented programming, design patterns, separation of concerns, reuse, encapsulation, testing and refactoring. Start at any of those and keep "plugging" away at the list and you will get better.

PHP specific - learn the accepted coding standard, such as PEAR's or Zend's. After you've assimilated some of the concepts, pick up a good reference such as one of the top frameworks mentioned in the other answers - Zend Framework, CakePHP, Symfony among others.

Eran Galperin
True, but this isn't really specific to PHP. PHP makes this difficult because the **default** behavior mixes implementation and interface. That's why I recommend a framework here, because it separates this.
Billy ONeal
+1 for your edit.
Billy ONeal
@Billy ONeal, I disagree about that being the "default" behavior. Even without a framework, a study of the concepts that Eran Galperin mentions would teach you not to mix implementation and interface.
bmb
@bmb: Default behavior of PHP takes plain HTML (the interface), and adds `<?php ?>` segments containing implementation, in the same file or logical module. Yes, there are ways to prevent PHP from doing this, but that is it's out-of-the-box, default, behavior.
Billy ONeal
Separation of concerns is a basic concept in programming. Learning how to separate logic from output generation is one of the learning steps in every programming language.
Eran Galperin
@Eran: Yes, I agree. I'm just saying that PHP's initial design was to do the exact opposite. That's why it's great as a template language but is relatively poor for anything else.
Billy ONeal
@Billy ONeal, it's a programming language. How does it have "behavior?" Especially "out-of-the-box" behavior? The language supports that paradigm, but it requires a programmer to write code.
bmb
@bmb: Err.. the behavior is the spec of the language itself. Other languages don't require you to "write code" that completely changes the rules of the language. Nor does any other language force you to write all code in what is essentially an interface file.
Billy ONeal
+3  A: 

To provide something other than "use a framework" or "look at a framework," here are quick rule-of-thumb PHP-specific practices I've found that make a big difference.

  1. Use PDO and abstract it into a class (or use an existing class). Do not use mysql_query or such functions.
  2. Logic before output. Do not do things such as <?php if($x) { ?> HTML here <?php } ?> (using HEREDOC syntax helps enormously with this).
  3. Use the __autoload magic method to limit includes

These alone would be night-and-day transformation of a lot of ugly PHP code I see. Then there are the obvious language agnostic rules such as consistent naming conventions, self-documenting code, etc.

Zurahn
+1 -- note that #2 becomes less important with some frameworks, where you're using PHP as a template language in a view. Actually, as a template language, PHP is pretty nice (considering that's what it was designed to be in the first place).
Billy ONeal
Referring to 2: You often need to do that in a view. Though `$x` is usually the result of something calculated in a non presentational layer.
alex
@Billy ONeal - Yes, and I think that's actually one of the best arguments for the use of a framework, though I still think it's worthwhile for PHP developers to be able to code cleanly enough with PHP outside a framework.
Zurahn
@Zurahn: Eventually, yes. But not for someone relatively new. (Or someone who doesn't wish to spend the time to learn enough PHP to care because they're forced to use it *cough*)
Billy ONeal
+3  A: 

Why does everyone attack php? Many many excellent sites run off it. At least until they get big enough to merit an overhaul.

99% of the internet is just throw away sites that don't get much traffic, compared to sites like facebook or amazon, so why should they care to learn a language more sophisticated, stable, or strict, if php gets the job done in a cost effective way that is no less stable or secure for what is needed?

Most of the sites I build run off Kohana - a branch from codeigniter. Both are useful. Who cares if CI uses php4. What if you get hired by a web firm that has archaic sites? Guess what - you will need to know php4. That complaint is like saying you no longer need to know tabled html... until you have to design and code a newsletter template for some big company. Then what? Crash course it with google searches?

I say the RIGHT way to use PHP is to follow examples. Yeah wordpress has some awful habits, but it works and is only one of the most successful platforms out there. What does that tell you?

I would say you could learn a lot from a framework like Kohana - and even CI - since both have decent security methods that are not hard to follow. Things like database escaping and xss filtering. It will ween you into OO programming if you are not familiar and both have a decent userbase so you will not get stuck with no answers.

Don't let these guys scare you. for beginners PHP is a good move. Eventually something like Java or objective C will be more beneficial for jobs and application, but learn it when you get there.

Kai Qing
Kohana started as a branch from CI, but is now a complete rewrite. Saying you may need to know PHP4 in the future does not make a good enough reason to learn it as a beginner. I may get a Ruby application, does that mean I should learn it now? Wordpress being popular has nothing to do with the quality of its code. Also *XSS Filtering* gives an incorrect notion - you should not try to filter, just encode based on context.
alex
Just because there are good things written in it doesn't make it a good language. On the contrary, often these things are good ideas implemented by poor- or non- programmers. And as far as "less secure" is concerned, you obviously haven't read 90% of the code snippets in the comments in the PHP docs :P
Billy ONeal
Oh, and the "right" answer is **NEVER** to "follow examples". I've seen more horrendously bad copy/pasted code because the person writing it didn't know anything about what the code was doing than any other code I've ever had to <s>destroy</s>play with.
Billy ONeal
"Tabled" html is plain *bad*. Anything you can do with tables for layout can be done without them in modern browsers, including multi-column newsletter templates that can *scale* as font size and browser width are adjusted - instead of some fixed-width fixed-font table layout. I'm no PHP expert but that statement about "tabled" html leads me to question everything else you claim. I do, however, agree with your general sentiment about learning.
Stephen P
... And? Yes, true to most of this, but again this does not make php a bad language. If Techplex learns CI at all he is in a much better position than most beginners. Any even mildly competent programmer will not be stumped by php4 elements and will compensate when necessary, and it's not like you need to master every element of php4 to understand CI. No, I haven't read 90% of the php docs. Who here has? I didn't say to copy and paste either. But if you actually read people's examples, an inquisitive mind will try and fail until they find their style.
Kai Qing
And Stephen - a MAJOR print and online publication hired us to do their html newsletter. In their proposal THEY stated the template MUST be in tabled html. Thank you. I agree that there are FEW - not none - instances where tables make sense, but it is not my world so I have to play by the rules.
Kai Qing
@Kai: I think @alex, myself, and @Stephen's points are that just because something is popular does not mean that is good, or something from which a beginner should be learning. It's "popular" to use `addslashes` to escape database inputs, but that doesn't mean it's the right thing to do. (In fact, it's the 110% *wrong* thing to do) Wordpress' popularity is more due to the fact that it is dirt easy to setup, not that it's easy for PHP programmers to maintain.
Billy ONeal
@Billy ONeal said it! [And so did many others](http://www.google.com/search?q=wordpress+code+sucks).
alex
Well, ideally people would take some CS classes and learn what is REALLY happening when their code is interpreted in any language, but that was not the question here. He did not ask IF he should use PHP but rather HOW. So PHP is not the best for data, memory or performance. It, unfortunately, is HEAVILY marketable, and is a forgiving playground for beginners. My point for wordpress is not that it is good but that it is SUCCESSFUL. Real byte nerds will always shun PHP. In the end, it's like complaining about porsches vs pontiacs. They both drive, so relax already.
Kai Qing
A: 

Firstly,You should read the php manual,then look open source software

Sam
-1: Nothing in the PHP manual says anything about best practices. It will teach you the language, but not how to effectively use it.
Billy ONeal
php manual says something about php
Sam
+4  A: 

The PHP community has never really been strong at offering up any development guidelines or advocating best practices. In the pre-framework days typical php code written by most devs was very amateurish and disorganized - see the Wordpress source code. But PHP is a good language for web apps. It was made for the web and you can write good professional code with it if you want to. It's trendy to bash it but disregard that stuff.

Anyway, like the others have said here your best bet is to use a framework. Being a newbie, it will be important for you to pick a framework that is well documented and has a strong community to help you get over the hump. Here's my rundown of the major php frameworks:

  • Kohana => a good one but poorly documented with a weak community. skip it.
  • Zend => the most popular framework for php w/good docs but another poor performer as it's overdone with objects and patterns in an attempt to be overly enterprisey.
  • Cake & Symfony => are 1st generation php frameworks and also have a rep for poor performance. I'd skip both. A new version of symfony is in the works but not ready.
  • Lithium => cutting edge new framework led by one of the Cake devs. using php 5.3 and claims to be fast. BUT, not at v.1 yet & also have poor docs at this point => http://lithify.me.

Codeigniter => popular, fast, good docs and community. very easy to learn. v2.0 hasn't officially been released but is ready for production use and is php5 only. You can use the same documentation that is on the CI site for v1.7. The versions are very similar except 2.0 drops php 4 support finally. here is the download for 2.0: http://bitbucket.org/ellislab/codeigniter/

YII => Really gaining momentum despite it's goofy name. It's a fast performer with GREAT documentation and a ton of features. A new book is out too. The community is so-so but growing. This framework imo takes a lot from rails. There a web-based code generation tool and it uses active record. http://yiiframework.com/

you can build apps a lot quicker with YII due to the code-gen and active record but it will be a bit harder to learn than CI. You may find it getting in your way a bit more too as you try to do everything the YII way. CI is more flexible - gives you the foundation you need w/o getting in your way. So for now i'd recommend codeigniter.

good luck!

johnW
I'm sorry, but this looks like a plug to me. More importantly, "disregard that stuff" -- so you're saying disregard any negative point for a language? That's an awfully short sighted philosophy. A good programmer understands their tools and their tools limitations, and uses the right tool for the job.
Billy ONeal
@Billy ONeal, you're being a troll.
staticsan
@Billy ONeal - Not a plug. I'd recommend CI to any php noob same way i'd recommend python to anyone looking for a first language to learn. The 'disregard' comment wasn't well said on my part. I wasn't refering to any specific advice but rather the overall php bashing by language purists. Despite it's shortcomings you can write professional, enterprise-grade code with PHP if you know how. It's not pretty like Ruby but it's a great tool for webdev and pragmatic people.
johnW
I'm not sure what is this obsession with benchmarks for frameworks, when it has very little bearing on scalability and overall performance. I've built major services (> 30 servers) using the Zend Framework, and the framework never was an issue. "overdone with objects and design patterns" shows your lack of understanding of what a good framework should be like. Choosing performance over good design and API is the worst kind of consideration for a web framework
Eran Galperin
@JohnW: Ok, +1. (And to your comment as well). The main reason I pointed that out is that too often we have fanboyism going on around here. So long as that wasn't your intention it's otherwise a good answer. I'm not trying to say that you can't write good PHP code, I'm saying that you have to do a relatively high amount of work (compared with, say, Python or something else) to write good PHP code.
Billy ONeal
@staticsan: How so?
Billy ONeal
@Eran "very little bearing"? You should read this. Make sure to check out the slides too: http://www.nowpublic.com/tech-biz/rasmus-lerdorf-simple-hard-drupalcon-2008-key-note Btw, YII has an excellent API AND it's fast.
johnW
@johnW Ramsus is known for his general dislike of frameworks. That's his privilege. In real world applications, the database and IO are usually the bottleneck for web applications, and very rarely does the application code is the problem (as long as you avoid the usual red herrings, like looping queries, etc). Picking a badly designed framework (CI) over a great one (ZF) for performance is a bad idea
Eran Galperin
@Billy ONeal, you've been adding a lot of comments along the lines of "PHP is a terrible language, but if you insist on using it, use this which fixes a lot of its flaws". Don't mistake me: this is a valid opinion. But it doesn't need saying again and again and again.
staticsan
@staticsan: I don't believe any comment I wrote in this answer said anything negative about PHP at the time of your comment. What I said was that there are things that SUCK about ANY programming tool/language. A good programmer is willing to acknowledge the faults of his platform even if it happens to be his or her favorite platform. That's true no matter what language you're using, be it PHP, C, C++, C#, Java, Python, Ruby, etc.
Billy ONeal
@Billy ONeal. Chill, dude. You're coming across as combative whether you intend to or not. I agree that there's a lot of shit PHP code out there because there are a lot of shit programmers who are just fundamentally unable to get any better. Frameworks *can* make things better but don't always.
staticsan
@staticsan: I'm sorry :P Hard to convey general attitude via text lol. Yes, frameworks aren't always the answer -- <stock quote>there is no silver bullet</stock quote>.
Billy ONeal
+4  A: 

It is possible to code well in PHP. Probably the best resource I've seen so far as to just how is here in StackOverflow: browse the questions marked PHP.

In no particular order, some specific things to help you on your way from my years programming in PHP:

  • Enable Notices and then make sure you don't write code that triggers them. PHP's default install doesn't enable Notices, which is fine for a Production environment, but bad for a Development environment. Unfortunately, their default php.ini file doesn't seem to know which it is being an example for.

  • Similarly, make sure you have magic_quotes and register_globals both turned off. They are both designed for more simple and naive programming times and today create more problems than they solve.

  • Initialize variables before you use them. This also means array elements. If your code isn't sure if the variable or element exists, use isset() and array_key_exists().

  • Pick or develop a sensible coding style and stick with it. You don't need to be frugal with whitespace or linebreaks.

  • Check for variables you are expecing to be there. This is a tricky one. A great example of this is when processing a HTTP POST that may have a lot of variable elements. Figure out what should be in $_POST and look for that. Don't assume that what is submitted is always going to be what is supposed to be submitted.

  • Along the same lines, check for the correct values, not the incorrect values. If you need a variable to have a valid value, look for what constitutes a valid value before proceeding, not what might be an invalid value to throw away. For example, if you need a submitted variable to be an integer, then check it's an integer, don't check for a null-string as a null-string isn't the only invalid value!

  • Separate database access, logic and presentation (this is often called Model-View-Controller programming). Another way of putting that is that you shouldn't be comixing code that is processing ther last POST request with HTML markup being emitted with SQL queries. Most frameworks will enforce this.

  • If you're not using a framework that provides an Object layer, you will be rolling your own SQL. Either use prepared statements, or use the DB's own quoting function for strings, not addslashes().

  • It was very easy in PHP 4 to use a lot of memory because structures got copied, not referenced. PHP 5 largely solves this specific problem, but it can still happen with strings. This also doesn't address the tendancy of some APIs to create large structures.

staticsan
+1 for the only answer referring to specific language features.
Billy ONeal
Yeah, this really is the the most logical answer. Wish I would have thought to say this instead of spewing some rant.
Kai Qing