Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 18
  1. #1
    Super Moderator
    Join Date
    Feb 2009
    Location
    England
    Posts
    539
    Thanks
    8
    Thanked 63 Times in 54 Posts

    How to write better PHP code

    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 Coding Forums.

    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[/php] tags, and your HTML, Javascript etc is surrounded by [code]html/js[/code]. 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 http://framework.zend.com/manual/en/...-standard.html - 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).
    Last edited by Inigoesdr; 07-11-2011 at 01:49 AM. Reason: Improvements
    lamped.co.uk :: Design, Development & Hosting
    marcgray.co.uk :: Technical blog

  2. The Following 8 Users Say Thank You to Lamped For This Useful Post:

    bergie (03-19-2011), BetraY (03-24-2011), bullant (03-08-2011), cyrus709 (03-28-2011), oesxyl (04-20-2011), paddyfields (03-09-2011), runeveryday (04-09-2011), x34cha (03-09-2011)

  • #2
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    maybe you want to add this:

    1.0 always use ini_set, 'display_errors' and error_reporting as long you develop your script, can be commented or removed when you deploy the script.

    2.5. always use mysql_error to see what't wrong with your query.

    4.0. develop and run shell scripts from php only if you don't have any other way to solve the problem

    best regards

  • Users who have thanked oesxyl for this post:

    Lamped (04-20-2011)

  • #3
    Regular Coder
    Join Date
    Dec 2007
    Posts
    145
    Thanks
    5
    Thanked 5 Times in 5 Posts
    People are far too lax with putting $_POST, $_GET, $_SESSION etc data directly into an SQL query.
    Don't forget $_COOKIE. In fact, I personally would replace it with $_SESSION. Most of the time people know what data they are placing into $_SESSION so it shouldn't be a problem there.

    I would also add to leave off the ending "?>".

    NBS
    Last edited by nobackseat88; 07-12-2011 at 09:08 PM.

  • #4
    New to the CF scene
    Join Date
    Aug 2011
    Location
    mohali, india
    Posts
    3
    Thanks
    0
    Thanked 2 Times in 2 Posts
    You don't need to remember functions, classes and specific solutions to be a good programmer. They are online, accessible at any time. And being a PHP developer you are unlikely to do much important work without being connected to the internet. Then what makes a good programmer? For me a good PHP programmer means someone who is efficient - who can solve problems and build quality web based software quickly and in a way that allows easier maintenance and extending of the program.

    So being a good PHP programmer means mostly to write a good code with less effort and time spent. And here is what does that mean - several main things:

    - Code that is short. I don't mean putting everything on one line like some Perl coders do, but writing less waste, reusing code and keeping it modular
    - Code that is easy to maintain and extend - this again means modular, but also a well commented PHP code.
    - Code that doesn't overload the server - you shouldn't get obsessed by this but it's important to keep the server overload low

    How to write such code? There isn't a specific recipe - every developer has its own style regardless the fact that many use frameworks or follow specific guidelines. So I'm not going to offer you a recipe. Instead of that here are seven of the best practices I follow to write better PHP (and not only PHP) code. If you use them too, you can drastically improve your efficiency as a developer.

    1. Use alternative PHP syntax in templates:
    I really hope you use templates, to begin with. If you are messing the HTML output directly into your scripts, you need to work on this first. If you already follow the concept to separate your design from the program logic, you are either using some template engine (usually a dead end reducing productivity) or placing a bit of PHP code inside the templates (loops, if/else statements etc). You can add some more cleanness to your views by using the alternative PHP syntax instead of the standard one with "{" and "}". Using foreach: / endforeach;, if: endif; for: endfor, etc. keeps the PHP code on less lines in the view, helps knowing when a loop is opened and closed and generally looks better.

    You can learn more about the alternative PHP syntax on the official PHP site - just search for "Alternative syntax for control structures".

    2. Everything capsulated:
    You know about the DRY, don't you? Don't Repeat Yourself. Don't copy-paste code. Always use functions and classes that will encapsulate often executed tasks. I know this is ABC of programming, but are you really really doing it? If one SQL query or code block is repeating itself 3 or more times in the application, then it should be a method or function. If it is repeating itself with slight variations, it should be a method or function as well (one that takes arguments). Here is what encapsulation gives you:

    - less code, less writing
    - ability to make changes across the entire app with a single code change
    - clean and understandable code

    These three things really make a better code. Let's get a very simple example: which you think is better - formatting the date in the SQL query or in the PHP code? Both are fine if you encapsulate the format. If you use the standard PHP date() function everywhere or the SQL date formatting function, passing the format that the client requires, to each call, what will happen if the client wants a change? You'll have to change it everywhere. To avoid that, build your own function to format the date or just put the formatting string (the "Y/m/d H:i A" thing for example) in a constant, so you can change it any time.

    3. Use a DB object:
    There are many ways to handle this, including ODBC, PDO and others. Whatever you do, don't put mysql_query() or mssql_query() (or whatever) directly in your code. It's not that you are going to change the DB engine ten times in the project - in fact in eight years in web development I had to change the DB engine of an existing project just a couple of times. It's again about keeping the code short, readable and better. For example I have a DB object with methods that return a single value, single array or multiple array from a DB query. This way instead of writing:

    $sql="SELECT * FROM some_table";
    $result=mysql_query($sql);

    and then using $result in some construction like while($row=mysql_fetch_array($result)), I just write:

    $sql="SELECT * FROM some_table";
    $some_things=$DB->aq($sql);

    And I have the result in $some_things. (Note: don't use this when retrieving thousands of records at once, it will exhaust the server memory).

    4. Use CRUD Functions:
    Just in case you don't know, CRUD comes from Create, Update, Delete. Create functions or object methods which will do this work for you or use the well known Active Record. Do this instead of writing long SQL queries with tens of fields listed. This is going to save you a lot of time. It's going to work automatically when you add or remove a field in the HTML form. Isn't that great?

    5. Debugging is your best friend:
    OK this point isn't directly related to writing a better code - it's more related to being a better programmer however. If something doesn't work, you are not likely to fix it just by thinking hard or by looking at hundreds of lines of code. It's not going to happen by swearing either. It's going to happen by debugging.

    Debugging is the action of going back following the logic of your program and finding the place where it works wrong or doesn't work. It doesn't matter if you use a debugger or just print_r() and echo() in various places of your code. The important thing is to trace backwards. Start from the current place - is there something wrong in it? If yes, go back few lines before the output/result happens. Is it still wrong? If yes, keep going few lines back. If no, then you know where exactly is the wrong piece of code - after this current line and before the line when your latest "is it wrong?" test returned true. I may sound bold, but I'll say that this is the most important skill in programming (and not only) ever: to be able to go back and trace the route of the problem. If you learn to do this, you will be able to solve any solvable problem.

    6. Mind the names:
    A code that uses meaningful variable names is so much better - at any time you read it you know what is happening - is there a product currently modified, is it an array of users, is it the ID of the logged in, or is it anything else. I am not talking about Hungarian notation - just use variable names which correspond to the subject they represent and show whether it's in singular or plural form. Don't use variable names like $rows, $row, $var Arr etc. Instead of that use $products when you are working with products, use $user when you are working with a single user, use $is_logged or $is Logged when you need a Boolean variable showing whether the user is logged in the system. Use names that matter and be consistent in that. You'll thank yourself later for writing such code. Other developers will thank you too.

    7. Reduce DB queries:
    It's a common sense, but how many developers really do it? How many of them spend hours improving some unimportant thing like moving a sizeof() out of a loop and at the same time send a DB query in the very same loop? DB queries are the most server power consuming task in many web applications. Here are several ways to reduce the number of queries in your code:

    - Use joins and left joins.
    - Use inner selects when joins and left joins won't do the job.
    - Use views and temporary tables.
    - Sometimes you'll need to check something for a number of records and the previous three solutions won't work. Instead of running a query each time, isn't it possible to run one query for collection A, one for collection B and then use a for each loop in PHP to check the condition? Very often it is. Be creative.

    Reducing the number of queries is vital for web applications that are going to be used by many users at the same time. Sometimes you may need to sacrifice code shortness for that. This will not make your code worse - you should give the things their correct priority.

    Are you following any of these guidelines in your code now?

  • Users who have thanked jhon786 for this post:

    cyberhostbd (09-26-2011)

  • #5
    New to the CF scene
    Join Date
    Sep 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks for the great tips!

    I love this point.
    "Sanitise your SQL. Use mysql_real_escape_string() or equivalent."

    Maybe a new thread about php security is also very helpful for many of us!

  • #6
    New to the CF scene
    Join Date
    Oct 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Not really a theme for "better php code", but perhaps for "better php applications":
    do unit testing and functional testing - development cycles in the so-called test-driven development (TDD).

    Some links for those who are interested:
    https://github.com/sebastianbergmann/phpunit/
    http://seleniumhq.org/projects/remote-control/

  • #7
    New to the CF scene
    Join Date
    Sep 2011
    Location
    West Coast
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Debugging is the action of going back following the logic of your program and finding the place where it works wrong or doesn't work. It doesn't matter if you use a debugger or just print_r() and echo() in various places of your code. The important thing is to trace backwards. Start from the current place - is there something wrong in it? If yes, go back few lines before the output/result happens. Is it still wrong? If yes, keep going few lines back. If no, then you know where exactly is the wrong piece of code - after this current line and before the line when your latest "is it wrong?" test returned true. I may sound bold, but I'll say that this is the most important skill in programming (and not only) ever: to be able to go back and trace the route of the problem. If you learn to do this, you will be able to solve any solvable problem.
    I can't tell you how valuable the above statement has been for me lately as I struggle with my self-taught php skills. Debugging is the key to troubleshooting, but also an important step in learning proper coding practices. It is time consuming but effective.
    Last edited by WA; 01-09-2012 at 04:42 PM.

  • #8
    New to the CF scene
    Join Date
    Mar 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by nobackseat88 View Post
    Don't forget $_COOKIE. In fact, I personally would replace it with $_SESSION. Most of the time people know what data they are placing into $_SESSION so it shouldn't be a problem there.

    I would also add to leave off the ending "?>".

    NBS
    just don't put the important ones in the $_COOKIE, because it would be a security threat to the user.. especially e-mail addresses.

  • #9
    New to the CF scene
    Join Date
    Nov 2012
    Location
    India
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Yes, actually it’s better to follow the style of the project where we are working on. If we work on a huge project and we are new there we should see its style and try to follow it, because other coders’ll thank us. Thanks for the comment!

  • #10
    Regular Coder LearningCoder's Avatar
    Join Date
    Jan 2011
    Location
    The Pleiades
    Posts
    919
    Thanks
    76
    Thanked 29 Times in 29 Posts
    Also to add, if you are getting unexpected results with variable values etc then always send it to var_dump(). This has helped me out a lot recently when working with arrays and strings.

  • #11
    New Coder
    Join Date
    Oct 2012
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts
    It is very important to write your programming code systematically so that each and every classes and functions are visible and accessible easily. Systematic code enhances the visibility and also allows other users to work on that code quite smoothly.

  • #12
    New to the CF scene
    Join Date
    Aug 2012
    Location
    New Delhi
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    How to write better PHP code:-

    I'm not going to offer you a recipe. Instead of that here are seven of the best practices I follow to write better PHP code:

    Some points:
    1. Use alternative PHP syntax in templates.
    2. Everything capsulated (separation of logic and display code; e.g. an MVC layout).
    3. Use a DB object, such as PDO.
    4. Debugging is your best friend. Helpful functions: var_dump(), die(). debug_print_backtrace(). Also review the PHP manual section on error handling.
    Last edited by Inigoesdr; 03-30-2013 at 02:04 PM. Reason: Added some more useful information

  • #13
    New to the CF scene
    Join Date
    Mar 2013
    Location
    Cebu City , Philippines
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Smile

    is PHP run by a server? what type of server ?

  • #14
    New to the CF scene
    Join Date
    Mar 2013
    Location
    Lhr, Pakistan
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thanks for the tips, these tips really matters a lot as I am learning PHP now a days.

  • #15
    New Coder
    Join Date
    Mar 2013
    Location
    Lucknow
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts
    This thread is very interesting and useful. I'm happy that I have found this thread.


  •  
    Page 1 of 2 12 LastLast

    LinkBacks (?)


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •