Thread Rating:
  • 2 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to write good php code [Must Read]
PHP General Guide

If you're reading this you're either looking for tips, or curious about what interesting stuff I can possibly add to an already amazing forum. I'm going to dispense some tips about general PHP development practices based on my experience, my experience with other developers and my experience with Zoince.

I will be adding to this post reguarly depending on what I've had to moderate in the last week, and comments I've recieved.

1. PHP

1.1. Formatting for the forum: This has been said so many times before. Please ensure your PHP code is surrounded by
PHP Code:
tags, and your HTML, Javascript etc is surrounded by
. This isn't just people being too lazy to read your code. There's a reason syntax highlighting editors are so popular: It makes it a HELL of a lot easier to read. Please do us all the courtesy of remembering this.

1.2. Controverial though it may seem, the community as a whole are following some vague variation of - I don't like all of it, and I don't expect you to either. I break some of their guidelines on a daily basis, but I have 10 years experience of reading my own PHP. Try and meet as many of those guidelines as you feel able to. It's not about some facist coding law, it's about standard ways of code layout that the majority of people can read easily.

1.3. To follow on from 1.1 and 1.2: Code that's easy to read is easy to support. If you want support, make it easy for people to help you.

1.4. Try and keep your HTML, CSS, Javascript and PHP separate from each other. It might look pretty to mix a dozen PHP code segments into your HTML, but I can assure you: It impresses no one. Do as much as possible in a separate PHP file, and make your HTML file use the absolute minimum of PHP. If that whopping chunk of PHP inside that lovely HTML table can be put into a function, in an included file, do it.

1.5. MVC: Read up on it, if you can. I'm not saying MVC is the best idea in the world, but it's good and it involves separating your HTML, PHP and Database specific code. This is always a great thing. Please read and consider this as it will, I promise, make your life easier later on.

1.6. Magic Quotes are the worst thing in the programming world, ever. This is a PHP feature that automatically puts a \ infront of ' and " in an effort to make SQL safer. It was a terrible idea when it was implemented. It's a terrible idea now. It will continue to be a terrible idea forever. If you actually use this feature and have no current plans to phase it out, please stand in line as there are hundreds of thousands of people wanting to slap you for it. See 2.1, 2.2 and 2.3.

1.7. Namespacing: Yes, there's a new feature in PHP 5.3 that allows a specific thing called "namespacing". You don't need 5.3 to implement a poor man's version of it. Do you want to write a function called "count()"? Yes, PHP already has a function called count, so you can work around it. What if you include a framework or file later that has the same function or class names? That's a pretty fast way to break a website. If you're working for Acme Inc, why not prefix all your code with acme? acmeCount() is much less likely to be in use than count(), and you'll know it's yours every step of the way. This goes for your javascript too: acme = {}; - put all your functions inside that {} and call them as acme.someFunction instead. It'll save you time and trouble later. There are other very good Javascript practices involving closures that I won't discuss here, but you might want to look up.

1.8. XSS and htmlentities: One of the most embaressing things that can happen to your site is an XSS attack. It's cross site scripting, which means someone has put a <script src="somethingbad.js"> on your site. Once such a script is on your site, it can redirect users to malicious sites, use social engineering to get malware on your users PCs and severely reduce people's trust in your website. When displaying something that could have potentially come from a user, please make sure you run it through htmlentities() first. Please.

2. MySQL with PHP

2.1. Sanitise your SQL. Use mysql_real_escape_string() or equivalent.

2.2. Sanitise your SQL. Use mysql_real_escape_string() or equivalent.

2.3. Sanitise your SQL. Use mysql_real_escape_string() or equivalent. Yes, this is worth 3 separate points. People are far too lax with putting $_POST, $_GET, $_SESSION etc data directly into an SQL query. DO NOT DO THIS. So many sites break with an apostrophe, it's actually quite depressing. Unless you can guarantee the data you're putting into the SQL doesn't include apostophes, quotes or somesuch, you should always sanitise it.

2.4. Look for a database abstraction layer. Google will help you with this, and most of them will help you sanitise your SQL properly. Using an abstraction layer also helps if you need to move from MySQL to Postgresql or MSSQL later.

3. Javascript with PHP

3.1. Sometimes people forget how separate Javascript and PHP really are. I strongly encourage people to write a fully functioning site with HTML, CSS and PHP, then and only then apply Javascript to improve it. You can never assume someone is running Javascript, or that your Javascript is running as you expect. You have full control over PHP. You have no control over Javascript, despite your best efforts.

3.2. A common issue with AJAX is caching. Unless you know better for your specific case, always disable caching in your AJAX library and PHP.

4. Bash/Shell with PHP

4.1. If you're developing a portable script, you should never, ever use shell_exec(), exec(), `` etc or any method that causes a program to be run on the server. Almost every time you think you need a shell script, look again and see if it's really necessary. You'd be surprised what can be accomplished in pure PHP, or with the help of a PECL addon. (Thanks to oesxyl for adding to this).

4.2. When running a command though one of the many PHP functions provided, I don't insist, I demand you run each and every parameter through escapeshellarg(). You'd be surprised how many websites are vulnerable to having their whole website wiped through some careless code.

4.3. File permissions are aren't just an annoyance, they're a useful tool to help against attacks like in 4.2. For most people, you want 0444 for a file you want readable but not writable or executable, 0666 is readable and writable by everyone. Directories have to be executable - executable for a directory means you can view the contents, so 0555 (readable and executable) or 0777 (read, write and execute). The first digit says "this is octal", nevermind if you don't understand octal. The second digit is for the file owner, the third for the file group, the fourth for everyone else. It's often dependant on the use of extentions such as SuExec and SuPHP. This is a complex topic that I may cover later in a more appropriate forum.

5. Debugging

5.1. Installing and using a debugger might take you an hour or two to get right. It'll save you twice that in the first week. Xdebug is a great tool, and having met the author, I can tell you he's a nice guy too! There are many editors that work with this. I have used Komodo IDE (my personal choice, though it's commercial), Netbeans, Aptana and Eclipse PDT and they all work reasonably well. I believe Komodo IDE is the best debugging IDE if you can afford it.

5.2. When debugging, remember to turn on "display_errors" and "error_reporting()", or check your logs. If you have shell access, "tail -f /path/to/your.log" is a handy way to watch your logs. (Thanks to oesxyl for this tip).

5.3. Remember, MySQL can be a black-hole of errors. Always check mysql_error() or mysql_errno() after your queries. Point 2.4 can help with this by converting MySQL errors into PHP errors or exceptions. (Thanks to oesxyl for this).

not my tut just sharing Thumbsup
Your sanitize won't fully protect against SQL injection, also javascript is fine, It's a must have for dynamic webpages! My panel is a lot of html css and javascript, then PHP for the login and live parts. If you're writing a huge website it's good to have a javascript and non javascript version like facebook. But yeah not a bad tutorial. Thumbsup
Need website or forum help?
[Image: logo.png]
very nice tutorial man this might come in handy

Aim = Pr8Source
This was so copied and pasted. LOL. but still kinda useful.
(06-14-2011, 02:24 AM)-Dreams Wrote: This was so copied and pasted. LOL. but still kinda useful.

LOL I Haven't Copied This
This is my tut
And Which other tuts i have copied i have mentioned the web from where i copied Huh
So far I have read two of your posts and they have helped me so thank you.
Another good practice with PHP is your indent style. It not only make sit easier to read, bu tit makes it easier to trouble shot where you left off a }, etc..

Great post though, thanks a bunch!
(06-27-2011, 07:48 PM)sidorak95 Wrote: Another good practice with PHP is your indent style. It not only make sit easier to read, bu tit makes it easier to trouble shot where you left off a }, etc..

Great post though, thanks a bunch!

Thanx Bro for posting another Link
Very nice and detailed guide.
I learned a lot!
Thanks Smile
Did you write this?

Possibly Related Threads…
Thread Author Replies Views Last Post
  PHP Framework List: An Ultimate Guide to 102 PHP Frameworks for Web Developers tk-hassan 0 847 07-27-2020, 11:26 PM
Last Post: tk-hassan
  PHP Video Tutorials (PHP For Beginners) Eleqtriq 4 3,400 10-10-2011, 01:00 PM
Last Post: Greyersting
  [CODE] Update Twitter using cURL and PHP Jamza 4 2,111 02-23-2011, 12:07 AM
Last Post: sup_hlw
  [TRICK] Write php codes inside .html files zone 14 4,486 04-26-2010, 01:38 AM
Last Post: JesusOfSuburbia
  Php Anti-DDos code tsgh mike 12 3,380 02-24-2010, 01:16 AM
Last Post: Jordan L.

Forum Jump:

Users browsing this thread: 1 Guest(s)