10 Things You Can Do to Become a Better PHP Developer

Embed Size (px)

Citation preview

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    1/15

    Skip site navigation

    HomeAll ArticlesTutorialsFreebies

    AboutContactSubscribe: RSS FeedFollow on Twitter

    10 Things You Can Do to

    Become a Better PHP Developer

    January 14th, 2011 by Raphael Caixeta | 41 Comments | Stumble It!Delicious

    PHP is probably the most popular web development language right now. At least 20 million domains use PHP and its the language used on majorsites such as Wikipedia and Facebook as well as in some of the worlds biggest open source projects like WordPress and Drupal.

    In this article, Ill share with you ten things I wish I was told when I was just getting started with PHP development, and Im hoping youll be ableto learn a thing or two if youre just taking your first steps into this awesome web development language.

    1. Use PHP Core Functions and Classes

    If youre trying to do something that seems fairly common, chances are, theres already a PHP function or class that you can take advantage of.Always check out the PHP manual before creating your own functions. Theres no need to create a function to remove the white space at thebeginning and at the end of a string when you can just use the trim() function. Why build an XML parser for RSS feeds when you can takeadvantage of PHPs XML Parser functions (such as xml_parse_into_struct)?

    2. Create a Configuration File

    Instead of having your database connection settings scattered everywhere, why not just create one master file that contains its settings, and theninclude it in your PHP scripts? If you need to change details later on, you can do it in one file instead of several files. This is also very usefulwhen you need to use other constants and functions throughout multiple scripts.

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to

    5 1/17/2011 1

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    2/15

    Using a config file is a popular web application pattern that makes your code more modular and easier to maintain.

    3. Always Sanitize Data That Will Go into Your Database

    SQL injections are more common that you may think, and unless you want a big headache later on, sanitizing your database inputs is the onlyway to get rid of the problem. The first thing you should do is learn about popular ways your app can be compromised and get a goodunderstanding of what SQL injections are; read about examples of SQL injection attacks and check out this SQL injection cheat sheet.

    Luckily, theres a PHP function that can help make a big heap of the problem go away:mysql_real_escape_string.mysql_real_escape_stringwill take a regular string (learn about data types through this PHP variables guide) and sanitize it for you. If youuse the function together with htmlspecialchars, which converts reserved HTML characters (like becomes ), notonly will your database be protected, but youll also safeguard your app against cross-site scripting (XSS) attacks when rendering user-submittedHTML (such as those posted in comments or forum threads).

    4. Leave Error Reporting Turned On in Development Stage

    Looking at the PHP White Screen of Death is never helpful except for knowing something is definitely wrong. When building your application,leave error_reporting and display_errors turned on to see run-time errors that will help you quickly identify where errors are coming from.

    You can set up these run-time configurations in your serversphp.ini file or, if you dont have access to override the directives in this file, setthem on top of your PHP scripts (using the ini_set() function to set display_errors to 1, but it has its limitations when done this way).

    The reason behind turning on error reporting is quite simple the sooner you know about your errors, the faster you can fix them. You mightnot care about the warning messages that PHP might give you, but even those usually signal towards a memory-related issue that you can takecare of. When youre done building out your application, turn error_reporting and display_errors off or set their values to aproduction-ready level.

    5. Dont Over-Comment Your Code

    Proper documentation of your code through comments in your scripts is definitely a good practice, but is it really necessary to comment everysingle line? Probably not. Comment the complicated parts of your source code so that when you revisit it later youll quickly remember whatsgoing, but dont comment simple things such as your MySQL connection code. Good code is self-explanatory most of the time.

    Good Example of Commenting

    Bad Example of Commenting

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to

    5 1/17/2011 1

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    3/15

    6. Keep Favorite Code Snippets Handy

    Youll be coding a lot of the same things throughout your PHP development career, and keeping code snippets always available will help yousave a lot of time. There are several apps that can keep and sync your code snippet collection for you, so no matter where you are, you canalways have your snippets available. Some apps you can use to corral your code snippets are Snippet, snippely, Code Collector, and Snipplr(web-based).

    Most integrated development environments (IDEs) such as Eclipse (which can store code templates) and Dreamweaver (via the Snippets Panel)may have built-in features for storing code snippets.

    Even a simple and well-organized directory called snippets that contain text files (or PHP scripts) and possibly synced in the cloud using anapp like Dropbox if you use multiple computers can do the trick.

    7. Use a Good Source Editor to Save You Time

    Your editor is where youll spend the majority of your time, so you want to use something that helps you save time. Syntax highlighting is a mustand definitely something you should be looking for as a software feature. Other bonuses include code hinting, code navigation and built-indebugging tools. All of these features can end up saving you massive amounts of time. An example of a source code editor/IDE for PHP isphpDesigner.

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to

    5 1/17/2011 1

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    4/15

    Take the time to get familiar with your source code editors features by reading the documentation and reading tutorials online. A bit of timeinvestment in this arena can really streamline your coding workflow.

    Check out this list ofsource code editors for developers as well as this list offree text editors for coders to discover popular code-editingapplications.

    8. Use a MySQL Administration Tool (Like phpMyAdmin)

    I know some crazy hard-core developers who like working with MySQL (the popular Database Management System pairing for PHP) viacommand line, which, to me, is inefficient and just, well, crazy. Its a good thing to know how to administer your MySQL database usingmysqladmin, but afterwards, you should use a graphical user interface like phpMyAdmin to speed up database development and administration.

    phpMyAdmin, in particular, is an excellent open source database viewer/manager that allows you to view your MySQL databases graphically sothat you dont have to waste t ime doing things via the command line. You can quickly build databases and their tables, export your databases intoSQL files, run SQL queries, optimize tables, check for issues, create MySQL database users and set up their privileges quickly, and much more.There is a good chance your web host already has phpMyAdmin installed, and if not, it only takes minutes to install.

    Check out this list of the best MySQL database management tools and this list ofMySQL apps for alternatives to phpMyAdmin.

    9. Use a PHP Framework

    It took me a really long time to accept the fact that using a web application development/rapid application development framework would helpme out. You have a small learning curve in the beginning, and there will be a lot of reading to do to learn how the API of the framework works,but you get amazing productivity and efficiency benefits later. Using a framework forces you to use better web development patterns that youmight not be using right now.

    Using a PHP framework pays off big time when you have to share your code with others later on or when you have to work together withsomeone; it gives you a standardized platform for building web applications. I learned the importance of this the hard way when I had to starthiring other developers.

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to

    5 1/17/2011 1

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    5/15

    Some popular PHP frameworks are CakePHP, CodeIgniter, symfony, and Zend.

    10. Connect with Other PHP Developers

    You dont know it all. And even if you think you do, there are thousands of others out there that know how to do something better than you do.Join a PHP community like PHPDeveloper and interact with others. By connecting with other developers, youll learn better ways of doing thethings youre currently doing.

    Related Content

    Learning PHP: Get Started Using PHPPHP Variables: The Ultimate GuideLearning PHP: Working with Conditional Statements

    Related categories: Web Development and Web Applications

    About the Author

    Raphael Caixeta is a PHP and iOS developer and co-founder ofGripd. He likes to blog about web and iOS development atraphaelcaixeta.com. If youd like to connect with him, you can follow him on Twitter @raphaelcaixeta and add him on Facebook(raphaelcaixeta).

    41 Comments

    Daniel H Pavey

    January 14th, 2011

    Nice list of tips for beginners.

    You were lucky to be told these, I had to work most of them out myself!!

    Mukesh

    January 14th, 2011

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to

    5 1/17/2011 1

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    6/15

    Great Info. Happy PHPing! :)

    Fix The Sky

    January 14th, 2011

    Very useful article. I know a lot of front end designers are reluctant to take a step into developing, but Ive found PHP to be a lot less daunting

    than it seems.

    Tomasz Kowalczyk

    January 14th, 2011

    Great article! I think that #10 is most important no one will keep you updated better than your friends doing the same. Everyone reads someRSS channels, and inform everyone else what he has found interesting. ;]

    Vivek Parmar

    January 14th, 2011

    Thanks for such a informative post. Im new to PHP and this post help me to become a better PHP developer

    Jacob Gube

    January 14th, 2011

    I love this, so spot on; I wish I knew these when I first started out as well.

    - Definitely study the PHP manual, youd be surprised at how many functions and classes come with core. You dont have to memorize themanual; but whenever you think of writing something to solve a task that you know a lot of sites must have already gone through before, yourfirst instinct should be to Google and see if theres already a function or native extension for it. Core has most of the things youll need to solvecommon web development tasks.- Dont over-comment code: instead, write expressive code and use a good code formatting standards (and if you dont want to develop one ofyour own, use something like PEARs coding standards). But its easy to get caught up with the semantics of coding standards, sofunction over

    form, whether its web design or PHP development.- Config file keeps your work tidy and easily maintainable.- Keep code snippets for sure. But today, my code snippets are PHP classes; if its something I reuse more than once (like MySQL dbconnection), Ill write a class for it.- If you dont have error reporting set up while youre in development, you are wasting your time, especially if youre a beginner. You will learna lot about how PHP works by learning about the errors you make.- A good source editor will make your life easier.- Use phpMyAdmin (after you learn how to administer MySQL through the CL). Personally, Im a visual person, so its hard to envision a tablestructure without actually seeing the tables and columns. And the CL is prone to mistakes if you havent had enough caffeine in your system yet.But using mysqladmin through the command line is good, fundamental knowledge.

    My other tips outside of the ones Raphael listed:- Use PHP classes; it can take a bit of t ime to really grok how they work, but once you learn it, it makes creating reusable and flexible codeeasier.- If you have to write it more than once, use include() and write that block in a PHP script. Dont overdo it though, its good to have afunctions.php file where you put collections of small utility functions into.- Develop locally using a server package like XAMMP (heres my tutorial for that) or WampServer (heres the tutorial for that). Its faster thanFTPing your files to the server, its safer, and its best practice to develop offline. Plus, if you have multiple apps or domains on the same server,you wont have to worry about taking them all down due to some bad script.- Learn about PHP patterns.

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to

    5 1/17/2011 1

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    7/15

    Jogi Silalahi

    January 14th, 2011

    thanks for the article. trying to be a good php developer. \m/

    Keir Davis

    January 14th, 2011

    This is a great list. I think you should have added Code Barrel (www.codebarrel.com) to the list of snippet managers in #6. It has an Eclipseplugin that works with Eclipse-based IDEs, like Zend Studio, which is a great PHP IDE.

    Prasad Prabhu

    January 14th, 2011

    very nice article and very apt for me since I am in my early of learning and developing web apps. Thanks. :)Please do share you PHP experiences in more blog posts, will be waiting for that.

    Jacob Gube

    January 14th, 2011

    @Prasad Prabhu: We could possibly do a follow-up on this, with more tips. I mean, these are probably 10 things out of hundreds that Raphaelcouldve to shared! :)

    And not to put Raphael on the spot, but Im also interested in reading about his iOS experience!

    And to others: If you have other tips you had to learn the hard way and wished you knew someone told you when you were first starting out,please share here in the comments!

    One more tip: I find print_r(), echo and var_dump() to be very rudimentary, but very helpful, tools for debugging your scripts. They are theequivalent ofalert() in JS, before you discover debugging tools like Firebug.

    DaveD

    January 14th, 2011

    Im not a huge PHP guy. I did some stuff back in the day and my most recent work was a WordPress blog, but I gotta ask: Ismysql_real_escape_string really the best way? Its easy to forget to get something quoted and lots of people will not do it on a field they knowis just an integer. Most of the problems Ive seen are of that nature.

    Though Ive not used it, isnt the mysqli extension a better way? It supports placeholders as I understand it and that always seems a better thingto me. That way you never forget to quote something.

    alex

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to

    5 1/17/2011 1

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    8/15

    January 14th, 2011

    I agree with most parts of your article, but sanitizing data only via: mysql_real_escape_string() does not protect you from sql-injection! It onlyadds a backslash before special characters like: or But for numeric values you dont need these characters, so you can write stuff like:&id=1 UNION and so on and inject your own code into the queryif youre not going to use a framework, i suggest you use Prepared Statements, then youre safe. =)

    Cheers

    Jacob Gube

    January 14th, 2011

    mysql_escape_string() isnt the only thing you should do to sanitize data, but, as the author states, it does protect you from a lot of the potentialsecurity vulnerabilities. So is it the best way? No, the best way is to learn about SQL injections and use a combination of methods (or use apre-built security class if youre not comfortable with this).

    keithics

    January 14th, 2011

    PHP Designer is an unrated PHP Editor, I just want every PHP developer to try it for a couple of days and see how good the product is.

    Lasix

    January 14th, 2011

    always check your input data on type matching. for example, you need int-type intval() function is your best choice!

    Young

    January 14th, 2011

    Very nice list! If youre a budding PHP developer, everything on this list is something youre going to google sooner or later. Im with Jacob thatmy snippets are now classes Ive coded some large sites procedurally and smacked myself in the head later when I discovered the beauty ofencapsulated OOP.

    @Alex: I agree with you in that if you are going to talk about SQL injections, you should mention prepared statements and not justmysql_escape_string(). I read somewhere that even then youre not completely safe

    @DaveD: I think PDO statements are the way to go to protect against injections. Ive found that MySQLi extension is rarely supported on sharedhosting.

    Proficiency in MVC and its patterns is probably my next hurdle. For someone who started with front-end languages, the idea of view controllersis really counterintuitive Teaching myself some iOS development has been helping me a lot to understand, since youre forced to use the MVCarchitecture for it.

    Ed

    January 14th, 2011

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to

    5 1/17/2011 1

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    9/15

    Good basic advice. I love the part about over-commenting code. Finding any comments are hard enough, getting to the point where youre indanger of over-commenting must mean youre close to reaching the mountain top.

    mario

    January 14th, 2011

    Thats definitely one of the few good recommendation lists. Im still divided on the frameworks though, as getting to know it doesnt often offsetthe time savings.

    @DaveD: Indeed. Parameterized queries are the way to go. While proper escaping works, the problem is that its too easy to overlook or forget.Theres however a usability problem with bound parameters and some query types, and due to lack of nice wrapper APIs (for PDO or mysqli)many PHP developers clinch to the outdated escaping methodology.

    Richard Smaizys

    January 14th, 2011

    In addition, you need to not only over comment your code, but also to keep up with rules that help you maintain and write better code. I thinkthat usually bad code writing habits make programmers worse than programmers who just creates bad structured website and etc. By the way,you can find a blog entry about how to improve your code style writing at my blog http://www.smaizys.com/programing/improve-your-code-style-with-simple-tips/.

    By the way there are filter_input() functions in PHP core which you might be interested.

    Breklin

    January 14th, 2011

    For the money, Navicat is hands-down the ultimate MySQL GUI. Saves tons of time. Automates backups and makes building a relationaldatabase a breeze. All for about a $100. Not bad.

    Jeremy Hutchings

    January 14th, 2011

    I thought of 10 in response to the sitepoints post that seem to of kicked a lot of it off :

    http://www.jeremyhutchings.com/2010/11/top-10-improvements-for-php-developers.html

    As well as 10 things you can do to support PHP itself, give back to a language that has given us so much :

    http://www.jeremyhutchings.com/2010/12/10-ways-to-support-php-payback-time-for.html

    Thomas

    January 14th, 2011

    1. use codeigniter (covers steps: 1, 2, 3, 4, 9).2. use codeigniter documentation, stack overflow, php.net and google (covers steps: 6, 10).3. use eclipse ide

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to

    5 1/17/2011 1

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    10/15

    4. use a mysql admin (heidisql [win], sequel pro [mac])

    you forgot to mention:5. use a personal web server for local development (MAMP [mac], wamp [win])

    WebTecker

    January 14th, 2011

    Im looking for a new IDE, how do you like phpDesigner?

    Paul

    January 15th, 2011

    Useful Tips! Thx!To work with mysql I use Toad for MySQL. Its freeware tool from quest.com.

    appukuttan

    January 15th, 2011

    Awesome post.. worth reading.. I alwyas thought it kinda hard. but this explains a lot :)

    Daquan Wright

    January 15th, 2011

    One thing Ive recently realized with phpmyadmin is that you get the best of BOTH worlds. You have a gui that lets you be efficient andproductivebut you can still write raw SQL code in the Query window if you prefer (I am for the purpose of learning SQL). To me that justmakes phpmyadmin even better.

    Glumbo

    January 15th, 2011

    Great list, I learned a few new things. Glad that you mentioned Drupal, for such a great system it doesnt have much exposure.

    alex

    January 16th, 2011

    @young:with prepared statements you should be safe, because the queries are precompiled.here a guy asks at the end how he hacks prepared statements, answer: prepared statements are not vulnerable to sql injection:

    http://www.securitytube.net/Advanced-SQL-Injection-%28LayerOne-2009%29-video.aspx

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to

    15 1/17/2011 1

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    11/15

    cheers

    ps.: if youre not using prepared statements i agree with Jacob Gube to use a ready-to-use class such as the filter-class from zend for instance.

    Andy Walpole

    January 16th, 2011

    Dont Over-Comment Your Code

    I disagree. Id rather see too many comments than too few. A lack of comments is more of a problem than an over-abundance.

    Craig

    January 16th, 2011

    Id add another to the list version your code.Youll need to do it in the future anyway.

    Working regular, structured commits in to my work flow made me a much more disciplined coder.

    Eric Bieller

    January 16th, 2011

    Some pretty good, although basic tips. I also strongly suggest using a framework like CakePHP. It cuts down development time immensely and iswell worth the taking time to learn how to use it.

    I would also add that learning the ins and outs of class functions and OOP can really help. Check out http://php.net/manual/en/language.oop5.phppretty much everything youll need to know.

    mike

    January 16th, 2011

    Dont sanitize content before you put it into the database. Sanitize it on the way out.

    Escape it on the way in.Sanitize at runtime.

    Cassiano Surek

    January 17th, 2011

    Frameworks are pivotal for productivity and standardisation. We use http://www.yiiframework.com/ and we love it. Choose one and stick to ituntil you know it very well.

    Eclipse IDE (with any supporting PHP module) can also help you maintain your snippets.

    Right after you address these 10 points, look into Test Driven Development (phpUnit et al) as it will perhaps be the natural evolution for adeveloper.

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to

    15 1/17/2011 1

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    12/15

    Kuboslav

    January 17th, 2011

    Instead of phpMyAdmin try use http://www.adminer.org/

    Jon Peterson

    January 17th, 2011

    I would like to suggest an appendix to number 4.

    Specifically, even in Live sites it is possible to access errors without confusing visitors, by using FirePHP (an extension/plugin for FireBug). Youshould check into it. You may find it worth adding to the article.

    Reference link (scroll to Error, Exception & Assertion Handling): http://www.firephp.org/HQ/Use.htm

    Jacob Gube

    January 17th, 2011

    @Jon Peterson: We were one of the first (and few) sites to cover FirePHP. Heres our tutorial on FirePHP:

    How to Debug PHP Using Firefox with FirePHP

    Chris Jokinen

    January 17th, 2011

    I have to disagree with #9. Frameworks add a lot of bloat and are not the ideal solution in many cases. You may save yourself time but it comewith a performance hit.

    Anurup

    January 17th, 2011

    The article is just amazing . Thank you so much

    Petr Kropotkin

    January 17th, 2011

    Excellent article. Might help me get more clients ;)

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to

    15 1/17/2011 1

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    13/15

    svbksocola

    January 17th, 2011

    Thanks, good job. I can see many thing for myself from your article. ^^

    Thomas

    January 17th, 2011

    Nice article however I agree with alex. Use prepared statements and NOT mysql_real_escape_string if your database supports them.

    Leave a Comment

    Name (required)

    email (will not be published) used for Gravatars (required)

    Website

    Subscribe to the comments on this article.

    Advertise Here

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to

    15 1/17/2011 1

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    14/15

    Search

    Topics

    AJAXCSSDesign Showcase / Inspiration

    FlashFreebiesGraphic DesignJavaScriptPhotoshopProject ManagementResourcesToolsTutorialsUsability / AccessibilityUser InterfaceWeb ApplicationsWeb DesignWeb Development

    Web StandardsWordPress

    Recent

    Are Current Web Design Trends Pushing Us Back to 1999?Five Things That Will Keep Shaping The Web in 2011Announcement: Winners of $300 in AlertFox Credit10 Things You Can Do to Become a Better PHP Developer10 Ideas for Creating Innovative and Unique Web Designs

    Buy our Book

    Purchase a copy ofMooTools 1.2 Beginner's guide on Amazon.com. Read more here. Also available on Packt and Barnes & Noble.

    Friends

    1stwebdesignerAddictive FontsAddToDesignApp SheriffBlog.SpoonGraphicsBrushLoversBurbiaChris WallaceCSS GlobeDesign BumpDesignOraDesignmessDesignM.ag

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to

    15 1/17/2011 1

  • 8/4/2019 10 Things You Can Do to Become a Better PHP Developer

    15/15

    Desizn TechfudgegraphicsFunctionInstantShiftLaptopLogic.comMarcofolio.netMyInkBlogNaldz GraphicsNETTUTSN.Design StudioNoupeOnextrapixelpsdfan.comPSDVIBEQueness[Re]Encoded.comSmashing AppsSmashing MagazineStylegalaSpeckyboy Design MagazineStylized WebTechnology.amTheBestDesigns.comVandelay DesignWalyou

    Web Designer HelpWebdesigner DepotWeb Design LedgerWPBeginner

    Become a Facebook Fan of Six Revisions. Advertise - Contact - RSS Feed 2008-2011 Six Revisions. Six Revisions mobile version by Mobify.

    hings You Can Do to Become a Better PHP Developer http://sixrevisions.com/web-development/10-things-you-can-do-to