Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with OpenID
Advertise on LowEndTalk.com

In this Discussion

How to write proper PHP

How to write proper PHP

joepie91joepie91 Member
edited July 2012 in Tutorials

Okay, there have been quite a few threads here about questions regarding PHP, and every time I see people making the same mistakes in their code. Considering there are probably quite a few people here that use LEBs for development stuff, I'll point out some good and bad coding habits, with solid reasoning as to why you should or should not do it, for each of them. Unless you can give a valid counterargument that proves the reasoning invalid, you do not have an excuse not to do shit.

As a first word, I'd like to point out something: Please stop letting your ego get in the way of writing proper code. Stop making up reasons as to why you wrote code a certain way ("that's by design", "but that isn't necessary because ...", etc.) just to not have to admit that your code quality was bad. If there is an issue with your code, then get over it, fix it, and learn from it. I expect others to tell me when my code sucks, and the other way around, I expect other developers to genuinely consider suggestions for their own code. The reason I point out code sucks is not to boost my own ego, but because I care about proper and secure code being written. There is simply too much crap code going around, even in many popular and commercial software packages.

Note that this thread should not be considered a complete guide, nor will I touch on subjects like sanitation - there are plenty of other guides for this. This is more about safe code syle than anything else.

Things you should be doing

Understand your code.

Try to understand your code. When looking at your code, you should be able to pick any line in your code and know exactly what data is in what variable, accurate to the byte. If this isn't clear, make your code clearer. Don't be afraid to use more variables to make it more obvious what your code does, variables are cheap.

Why? By understanding your code, you will be able to spot bugs and vulnerabilities just from looking at it. It will take some time to get skilled at this, but eventually every single bug will be blatantly obvious to you, even if you're looking at code you wrote a year ago.

Indent your code.

Always, always, always indent your code properly. That includes PHP, that includes HTML, that includes CSS, that includes every single language that allows you to indent code. "It's not public code" is not a valid reason not to indent.

Why? Properly indented code allows you to see the structure of your code at a glance, and improves readability. Improved readability and understanding of code results in less bugs and less vulnerabilities. You should be able to understand what your code is doing at any point, just by looking at it, this makes it easier.

Use proper spaces.

While I can't tell you what your coding style should be, I do have some suggestions that would be a good idea idea to follow, to improve readability of your code.

$variable_name = some_function($something_else, $another_thing);

Leave spaces around assignment and equality operators, this makes it clear what part of your code belongs together. Don't add unnecessary spaces around braces, this will only make it less visible what belongs to what.

Why? This makes it obvious what part of your code belongs to what, and what the relationship between various elements is.

Use clear variable names.

Don't abbreviate variable names. There is no valid reason to do so. Make it clear from the name of the variable what's inside it. $unm is not a valid variable name. $username is a valid variable name, as it makes it obvious what is in it. $username_of_the_logged_in_user is far too long and makes your code hard to read; you could've used the much shorter $username.

Why? It allows you to see at a glance what a variable does. If you need to go to another line to see what a variable contains, you're doing it wrong.

Use proper braces.

Never ever ever leave out the curly braces around a code block. I don't care if it's one line or not, do not ever leave them out. Always enclose code blocks that belong to control structures in braces. Preferably, give each brace its own line as it makes it obvious what opening brace belongs to what closing brace.

Imagine you have this code:

if($confirm_delete === true)
     delete_item($_GET['id']);

Oops! The delete_item() function expects an integer, not a string. Well, let's just solve it like this, right?

if($confirm_delete === true)
     $id = (int) $_GET['id'];
     delete_item($id);

Whoops, you didn't realize that you weren't using braces, and now the item gets deleted regardless of whether $confirm_delete is true!

Why? People make mistakes, especially when in a rush. Don't think that "you wouldn't ever make the mistake above', because you will, at some point. Don't take the risk and just be safe and enclose it in braces; there is not a single reason not to do so.

Use curly braces for inline variables.

This trick isn't very well-known, while it should be. Say that you're using a variable inside a string, like so:

$whatever = "Hi, $something!";

Instead, do this:

$whatever = "Hi, {$something}!"

Why? There are many reasons to do this. 1. It will ensure that any characters that come after the variable name are not taken into account when parsing. 2. It makes it more obvious that a variable is a variable, which makes it easier to spot mistakes in things like queries. 3. Consistency. When using an array item in a code block, you enclose the key in apostrophes. To do the same in a string, you need to use curly braces. Logically, it makes sense to then enclose both array items and regular variables in apostrophes.

Stuff you really shouldn't be doing

Obfuscating your code.

No, obfuscating will not secure your code against 'hackers'. All it will do is make your code harder to read and understand - which actually makes it more likely that new vulnerabilities are introduced that you don't notice. Security through obscurity is not security.

Using exec() to do anything other than launch processes.

It's pretty likely that you can do whatever you want to do, with a PHP function. Don't use exec.

Other tips

Use a code editor.

While you can technically use notepad or nano to edit your code, it's not a very good idea - it doesn't do auto-indentation, and doesn't color-code your code, which makes it harder to spot mistakes.

A few suggestions for light-weight code editors: Windows: Geany, Notepad++, Sublime Text Linux: Geany, Vi, Sublime Text OS X: Sublime Text

Not sure if your code is good?

Post a code sample below, and I will read it, suggest improvements, give the reasoning behind those suggestions, and if applicable, update this initial post.

Something unclear?

If it's not clear to you why I am recommending a certain practice, or you think the reasoning isn't solid, then by all means point it out! I will attempt to clarify and take into account your concerns, and update this post accordingly.

Thank you for reading.

Appreciate my posts/software/guides? Donate (PayPal/Flattr/Bitcoin): http://cryto.net/~joepie91/donate.html | irc.freenode.net #lowendbox

Comments

  • Everyone has their own techniques and best coding practices, old habits die hard.

    I double space instead of using tabs, and put braces on the same line which is perfectly fine still.

  • @AsadHaider said: Everyone has their own techniques and best coding practices, old habits die hard.

    I double space instead of using tabs,

    Hence my use of the word 'indentation' as opposed to 'tabs' :)

    @AsadHaider said: and put braces on the same line which is perfectly fine still.

    Which is fine, as long as you can interpret your code properly. Generally speaking if someone can bring up a valid reason as to why he puts braces on the same line, he's competent enough to make that decision. Sadly, most people aren't. The incompetent developers - which sadly make up a large part of the developer community - are mostly those I target with this thread.

    Appreciate my posts/software/guides? Donate (PayPal/Flattr/Bitcoin): http://cryto.net/~joepie91/donate.html | irc.freenode.net #lowendbox

  • PADPAD Member
    edited July 2012

    This is aimed at every code nazi out there.

    Understand your code

    If I didn't already understand my code I wouldn't really want to code.

    Indent your code

    No, professionally yes you should if others are going to be reading/changing I think this is great but honestly your reasoning for this point is absolute BS - If I like my code laid out a certain way then I will lay it out that certain way, no one is going to tell me there is one single solution to make my brain click. I code the way I code and whether it adheres to your indentational rules are non of my concern.

    Use proper spaces

    Same thing as above really, there is no 'proper' there is only majority, if I'm the only one seeing it then what matters to me is the most important rule of thumb, this is not an excuse, this is a simple reason.

    Use Clear Variable Names

    Once again, 'clear' depends on who it is clear to, do you think that an alien language would be clear to us if we stumbled upon another inhabited planet? I mean this all falls under the same thing, you're advising we do something based on majority when you clearly state above that we should do this whether only we lay eyes on the code or not. This is stupid.

    Use proper braces.

    I can't see how you could code or call yourself a coder or even dabble in code without knowing this, since every example on the face of the planet will set an example, auto-completion engines will recommend this, in general this is something that should come natural to anyone and everyone, its not really advice.

    Use curly braces for inline variables.

    This is another "eh, wtf?" point - it is not needed and depends entirely upon the coder, your last point is valid but still not required, all others are pure preference, how YOU read it and not the subject in question.

    THINGS TO NOT DO ___

    Obfuscation

    I agree. But if you're editing the obfuscated version you're fucking retarded.

    Using exec() to do anything other than launch processes.

    No sh!t sherlock - you love reinforcing the obvious.

    Not sure if your code is good?

    Code can be inefficient, messy to your (the end users) eye, but there is no 'good' or 'bad' code inherently, it once again depends on the coder, the situation/scenario, the effort one desires to put into something, you guys that go nazi on everyone and demand that there is a gold standard in every circumstance are just idiotic.

    Something unclear?

    Nothing is unclear, almost everything you recommended is useless and/or relies on the situation, of which it cannot be applied to.

    Sorry for the hate, but honestly this stuff is stupid.

  • joepie91joepie91 Member
    edited July 2012

    @PAD said: This is aimed at every code nazi out there.

    Understand your code If I didn't already understand my code I wouldn't really want to code.

    @PAD said: Use proper braces. I can't see how you could code or call yourself a coder or even dabble in code without knowing this, since every example on the face of the planet will set an example, auto-completion engines will recommend this, in general this is something that should come natural to anyone and everyone, its not really advice.

    Do you really think I would have added it to this list if I didn't run across people not understanding this this very day? Sorry, but I think you misunderstand the purpose of this thread.

    @PAD said: Indent your code No, professionally yes you should if others are going to be reading/changing I think this is great but honestly your reasoning for this point is absolute BS - If I like my code laid out a certain way then I will lay it out that certain way, no one is going to tell me there is one single solution to make my brain click. I code the way I code and whether it adheres to your indentational rules are non of my concern.

    Use proper spaces Same thing as above really, there is no 'proper' there is only majority, if I'm the only one seeing it then what matters to me is the most important rule of thumb, this is not an excuse, this is a simple reason.

    Use Clear Variable Names Once again, 'clear' depends on who it is clear to, do you think that an alien language would be clear to us if we stumbled upon another inhabited planet? I mean this all falls under the same thing, you're advising we do something based on majority when you clearly state above that we should do this whether only we lay eyes on the code or not. This is stupid.

    @PAD said: Use curly braces for inline variables. This is another "eh, wtf?" point - it is not needed and depends entirely upon the coder, your last point is valid but still not required, all others are pure preference, how YOU read it and not the subject in question.

    Congratulations on fully ignoring the entire reasoning given for each.

    @PAD said: Using exec() to do anything other than launch processes. No sh!t sherlock - you love reinforcing the obvious.

    I suggest you have a look at this thread.

    Now onto your attitude in this thread. I find it quite disrespectful that in a thread that is intended to be helpful and even explicitly calls on developers to forget their ego for a second, the only thing you do is trying to boost your ego by calling other people idiots and bitching about how noone has the right to tell you what to do.

    Come back when you have constructive criticism.

    Appreciate my posts/software/guides? Donate (PayPal/Flattr/Bitcoin): http://cryto.net/~joepie91/donate.html | irc.freenode.net #lowendbox

    Thanked by 1haris
  • Don't forget the IDE or text editor used. Notepad or nano vs Notepad++ or Vi.

  • joepie91joepie91 Member
    edited July 2012

    @AsadHaider said: Don't forget the IDE or text editor used. Notepad or nano vs Notepad++ or Vi.

    Good point, let me add that.

    EDIT: Added a few editors.

    Appreciate my posts/software/guides? Donate (PayPal/Flattr/Bitcoin): http://cryto.net/~joepie91/donate.html | irc.freenode.net #lowendbox

  • PADPAD Member
    edited July 2012

    @joepie91

    Not at all, I'm not even experienced enough to class myself as a full on developer, my ego was not at all engaged in this thread, honestly dude I just don't like to see this level of enforcement on such issues - you didn't actually list anything half decent, just things which relate entirely to the situation in which we (the coder) is coding, the project, etc.

    And there is no constructive criticise if I'm honest, your advice is crap and not in the correct context. I get it, understand it, but it doesn't fit. You're advising someone on how to do A when generally its perfectly fine to do B C D E F and G depending on exactly what you are actually trying to achieve. Anyway not being constructive so to speak would have included me pasting some one-liner about your thread, instead I gave you all of my opinions, which are worth a lot more than any other crap I could have chosen to spew out.

  • debugdebug Member

    I actually like using single quotes for strings, so I do:

    echo 'Hello, '.$something;
    

    Hello, World.

  • PADPAD Member
    edited July 2012

    @debug

    Once again, there is proof of my points all over, in reality it is about how to coder perceives his code, if you don't expect speculation of your code, you should NEVER worry about how it looks, as long as it makes sense to you.

  • joepie91joepie91 Member
    edited July 2012

    @PAD said: Not at all, I'm not even experienced enough to class myself as a full on developer, my ego was not at all engaged in this thread, honestly dude I just don't like to see this level of enforcement on such issues - you didn't actually list anything half decent, just things which relate entirely to the situation in which we (the coder) is coding, the project, etc.

    Your initial response came across extremely egocentric, as do most of your posts on LET.

    @PAD said: And there is no constructive criticise if I'm honest, your advice is crap and not in the correct context. I get it, understand it, but it doesn't fit. You're advising someone on how to do A when generally its perfectly fine to do B C D E F and G depending on exactly what you are actually trying to achieve.

    Then feel free to suggest alternatives with solid reasoning behind them. Just saying "no, you can do it otherwise" doesn't cut it, as it doesn't at all address the issues I'm pointing out.

    @PAD said: if you don't expect speculation of your code, you should NEVER worry about how it looks, as long as it makes sense to you.

    People are notoriously bad at judging the readability of their own code. Please find me two developers that can honestly say they can easily read the code they wrote 3 years ago.

    Appreciate my posts/software/guides? Donate (PayPal/Flattr/Bitcoin): http://cryto.net/~joepie91/donate.html | irc.freenode.net #lowendbox

  • PADPAD Member

    @joepie91

    Well I'm sorry, but I feel if I'm going to spout my brain out I may as well do it how I enjoy it, if I have something bad to say then I'll say it. All of my posts will seem cocky and egotistic because I don't fear judgement and if I need or want to say something then I will. That is kind of the point of a forum, debate, discussion, being up front is just how it works for me, I could always sugar coat my replies but that would be of no benefit to either of us, because my real thoughts would be just the same.

    And I can see that, maybe I'm just different, I don't really have a problem understanding or re-reading my code. I can definitely imagine how others would have trouble though.

  • ztecztec Member

    Hey Joepie91,

    I'm pretty sure you are dutch and regarding that I have a question for you; to what uni / school are / were you going?

  • Giving advice on how to write proper PHP code is like tuning a North Korean car.

    President Of Operations/CEO/CFO/CTO/COO of my account
    image

    Thanked by 1djvdorp
  • How to write proper PHP
    <?php .... ?>
    Yes! I'm with Carstensz Pyramid Server Now stop asking me please :D
    Thanked by 2yomero yeradis
  • DamianDamian Member

    @joepie91 said: Using exec() to do anything other than launch processes. It's pretty likely that you can do whatever you want to do, with a PHP function. Don't use exec.

    This is my favorite one. PHP is so far advanced that there's very little that you need to do a system call for. A favorite example is making archives. PHP includes Phar, and Pear has the Archive_xxxx functions, and for archives like zip, it's built in. No need to do system calls to make archives ever.

    I am no longer affiliated with IPXcore.
  • I agree with this thread; however with any language, you pick up habits from when you first learned. It isnt something that can be re-taught or made better, if I want to comment every line, that's me. If @Damian wants to throw @HalfEatenPie's at it, that's up to him.

  • @eastonch said: If @Damian wants to throw @HalfEatenPie's at it, that's up to him.

    That's not very nice! Pies have feelings too!

    Catalyst Host - Pie Approved!
  • PatsPats Member

    these days its creating sleepless nights to Wordpress, Joomla users with their site getting hacked/defaced every now & then...

    @joepie91 said: with a PHP function. Don't use exec

  • PatsPats Member
    edited July 2012

    @HalfEatenPie said: That's not very nice! Pies have feelings too!

    OMG ! feelings for? @Damian ?? :P

  • heiskaheiska Member

    You should learn to indent your code even when using PHP as e.g. Python uses indentation (four spaces) instead of braces to determine the structure of the code.

  • @HalfEatenPie's don't have feelings; only full pie.

  • @heiska said: You should learn to indent your code even when using PHP as e.g. Python uses indentation

    That's not a valid reason. PHP is PHP, Python is Python. It's a good habit to have, but the existence of Python alone doesn't somehow require you to use indentation in PHP.

    @heiska said: (four spaces)

    No. This is recommended by a PEP (8?) but it is not actually required by Python. Any kind of indentation (any amount of spaces, or tabs) can be used, as long as it's consistent.

    Appreciate my posts/software/guides? Donate (PayPal/Flattr/Bitcoin): http://cryto.net/~joepie91/donate.html | irc.freenode.net #lowendbox

  • specklspeckl Member

    I would recommend adding comments above each function. I also comment the end of lines of code that I may need to look at later on down the road.

    UK VPS's 15k SAS drives - http://httpzoom.com

  • yomeroyomero Member

    Ok, reading all the flame stuff.

    Both guys stop your ego. Yes, both. And I don't want to quote old comments on how you behave.

    On topic, I think we must change the title for "MY PERSONAL recommendations/suggestions/tips for coding".

    And as a personal opinion, I do most of these too, all are useful.

  • @speckl said: I would recommend adding comments above each function. I also comment the end of lines of code that I may need to look at later on down the road.

    Actually, comments are typically a sign your code isn't clear enough. While there are cases (even in languages like PHP) where it's really just nearly impossible to write clear code, your code should generally be self-explanatory and not even need comments - something that is very achievable in PHP, Python, or basically any other 'high-level' language.

    Appreciate my posts/software/guides? Donate (PayPal/Flattr/Bitcoin): http://cryto.net/~joepie91/donate.html | irc.freenode.net #lowendbox

  • MrDOSMrDOS Member
    edited July 2012

    There's a number of things wrong with PSR, but for lack of a better style guide, they're worth reading through at least to consider the pros/cons.

  • netomxnetomx Member

    Lol, calling my phrase and not quoting me? I'm gonna sue you.

    And I used exec because I didn't knew that function, thanks for showing me that.

    And leave my brackets alone!

  • telephonetelephone Member
    edited July 2012

    @joepie91 said: Actually, comments are typically a sign your code isn't clear enough. While there are cases (even in languages like PHP) where it's really just nearly impossible to write clear code, your code should generally be self-explanatory and not even need comments - something that is very achievable in PHP, Python, or basically any other 'high-level' language.

    Yes and no. While code readability should be #1, When dealing with large projects it's helpful to be provided with a summary of the function/class instead of reading line by line to become reacquainted. This is also justified as coders continually hone their skills, and change their coding structure/format. There are plenty of times I've gone back to code I produced a year ago and couldn't understand the logic I implemented.

    @joepie91 said: Use curly braces for inline variables.

    As debug mentioned there are many different ways to differentiate variables between strings.

    When using double quotes, curly brackets are useful if you wish to differentiate variables/characters that touch without concatenating:

    echo "This is my $string" . "! It says $hi";
    vs
    echo "This is my {$string}! It says $hi";

    In fact, double quotes should only be used when one's wanting to include escaped characters or variables:

     echo "This is my string, look at how pretty it is.";
    should become:
    echo 'This is my string, look at how pretty it is.';    // no need to parse a simple string

    Compare this to:

    echo 'LET\'s becoming' . $adjective . '. Which can be ' $adjective;
    vs
    echo "LET's becoming $adjective. Which can be $adjective";

    One can even argue that concatenating a string/variable is slower than passing arguments while using "echo":

    echo 'This is my ' . $string . '! It says ' . $hi;    // slower
    vs
    echo 'This is my ', $string, '! It says ', $hi;    // faster
    Thanked by 1yomero
  • dwilddwild Member

    @joepie91 said: Actually, comments are typically a sign your code isn't clear enough. While there are cases (even in languages like PHP) where it's really just nearly impossible to write clear code, your code should generally be self-explanatory and not even need comments - something that is very achievable in PHP, Python, or basically any other 'high-level' language.

    Did you actually work professionnaly on huge project? You don't have time to read each code that everyone write. You don't comment to explain how it work, you comment to explain how to use it.

    Thanked by 1djvdorp
  • @telephone

    that's something useful i was going to post, if you haven't

    it does a huge difference when you code has to burden heavy load

    writing clean code even for your own eyes is just getting an habit to do it everytime

    single vs double quotes, dot vs coma concatenation (php speaking) must became an automation, even if sometimes they're less readable: it's a trade off to the right side of the fence

    @joepie91

    there's something you totally forgot: api consistency. you can put every braces you want, if you start swapping params order in your signatures, if you change variables name for the same data from function to function, you're wasting your diligence ;1

Sign In or Register to comment.