How not to PHP



  • So, one gallery script written in PHP is being phased out and a friend of mine is looking for a replacement, and he was investigating ZenPhoto.

    The code he has shown me - which I gather is current - is how not to PHP.

    $('#<?php echo $key; ?>_colorpicker').farbtastic('#<?php echo $key; ?>');
    
    $userobj = Zenphoto_Authority::getAnAdmin(array('`user`=' => $user, '`valid`>' => 0));
    

    Double points for sending that semi-directly to the database.


    if (method_exists($optionHandler, 'handleOptionSave')) { 
                        ?> 
                        <input type="hidden" name="<?php echo CUSTOM_OPTION_PREFIX; ?>save-<?php echo $whom; ?>" value="<?php echo $extension; ?>" /> 
                        <?php 
                   }
    

    Then to encode things in $\_POST, we have this jolly little number: ``` return strtr(urlencode($str), array('.' => '__2E__', '+' => '__20__', '%' => '__25__', '&' => '__26__', "'" => '__27__')); ``` This makes no sense to me to do under any circumstances.

    I haven't seen the code in person but this is simply evidence of why I won't touch this particular package with a 10ft barge pole.



  • I think the only way not not to PHP is to not PHP.

    PHP now stands for "Not Even Once".

    *Edited for clarity



  • No, PHP isn't entirely terrible. It's only mostly terrible and it is possible to write sane things in it. It's just very good at letting people in who should never be let near programming.


  • Winner of the 2016 Presidential Election

    @Arantor said:

    $('#<?php echo $key; ?>_colorpicker').farbtastic('#<?php echo $key; ?>');

    Is the problem here that he put echo inside Javascript and thats terrible if you do it a lot?

    @Arantor said:

    $userobj = Zenphoto_Authority::getAnAdmin(array('user=' => $user, 'valid>' => 0));

    Havig not worked with Zenphoto ever... what does getAnAdmin expect and what does it do with it? Why would you allow an array to be sent do your function that then does things to the database like this?!

    Next point once again portraits the "mix html and PHP" right? Because I have done that, too when I was young and stupid. Depending on the size of your project that should not even matter, right?

    @Arantor said:

    return strtr(urlencode($str), array('.' => '2E', '+' => '20', '%' => '25', '&' => '26', "'" => '27'));

    You said it was to encode things in $_POST.... but I don't even understand what it is trying to do. What does it attempt to do (besides encode things?). What would be a better way to do something like this?

    Is this code how the package expects you do write PHP? Is your friend the person who writes terrible PHP? Is this gallery the only one available? Am I missing anything obvious?

    Filed Under: <?php echo $Filed_Under_Message; ?>



  • The first one is that you're going from HTML-with-JavaScript to inside PHP just to echo a fucking variable.

    The second one... I don't know. But judging by the use of backticks and the commentary that went with it, it's setting up to see if the current user is an admin and passing in what looks suspiciously like raw SQL clauses.

    The third one, I have no idea why you would do it that way. urlencode converts most non-alphanumerics to %xx syntax for the URL. I have no idea why they insist on converting some of the rest into some bastardy of urlencoding.

    This package is an off-the-shelf gallery script, my friend was evaluating it as a replacement for Gallery2, and he was just trying to make sense of it and essentially writing it off as a suitable replacement. My friend writes generally quite sane PHP, though doesn't get into big scary stuff.

    There are others, but Gallery2 (and Gallery3) are being discontinued, ZenPhoto was the first one he started looking at. Onwards to the next one, I guess.



  • @Arantor said:

    The first one is that you're going from HTML-with-JavaScript to inside PHP just to echo a fucking variable.

    Since I've done this before, what's the correct way?



  • If you don't have any template language of any kind, it's a toss up between that and using an echo PHP side.

    But I'd argue that some kind of template language is bordering on a necessity for any non-trivial project simply because done properly it helps you separate presentation from other logic and can also help mitigate overall risk re XSS.



  • I can highly recommend 4images for all of your gallery needs.



  • Thanks but I don't think that's quite what my friend is looking for ;)


  • 🚽 Regular

    Original:

    $('#<?php echo $key; ?>_colorpicker').farbtastic('#<?php echo $key; ?>');
    

    Alternative 1 (single-quoted strings don't do interpolation):

    <?php
    echo '$(\'#' . $key . '_colorpicker\').farbtastic(\'#' . $key . '\');';
    ?>
    

    Alternative 2 (doubled quoted strings do interpolation):

    <?php
    echo "\$('#{$key}_colorpicker').farbtastic('#{$key}');";
    ?>
    

    Alternative 2 is IMO the most readable. Pay no attention to DC highlighting the "#" characters as if outside the string.

    Back when I did PHP I was also a fan of heredocs (again, pay no attention to the highlighting):

    <?php
    echo <<<HTML
    \$('#{$key}_colorpicker').farbtastic('#{$key}');
    HTML;
    ?>
    

    My 0.02 €

    Edit: missing .


  • 🚽 Regular

    Btw, don't take my previous post as patronizing.

    I assume people who don't know PHP read the post too.



  • No problem, I asked because I'm a PHP newbie.



  • @Arantor said:

    $('#<?php echo $key; ?>_colorpicker').farbtastic('#<?php echo $key; ?>');

        $(<?= json_encode("#{$key}_colorpicker") ?>)
                .farbtastic(<?= json_encode("#{$key}") ?>);
    


  • Requires short tags to be on which isn't always on shared hosts.



  • As of 5.4, <?= is always permitted.



  • Don't use 4images... I reported an issue I've found in its convoluted XSS filtering code in about 3 minutes of skimming the source code, and a few months later they still haven't fixed it.
    I haven't looked any further, but they don't seem too aware about security.
    (I haven't actually tried to exploit the issue - the XSS filtering function simply doesn't always filter most of the stuff it should, I assume that causes XSS along the way)



  • +1 for suggesting json_encode to take of JS string quoting oddities.



  • Fix: use .NET or Python



  • @Arantor said:

    <?=

    Comes down to legacy code since 5.4 is "recent"



  • I like PHP. Yes, it's really, really flawed, but what isn't in this crazy world?

    However, I am now proud to announce I've fled the open sewer that is the FOSS world and now do C# development on drone control software.

    "If it's small and brown, gun it down. If it's a caucasian you see, let it be."



  • @morbiuswilters said:

    I like PHP. Yes, it's really, really flawed, but what isn't in this crazy world?

    Python.

    Also, I get the feeling that you work in my town.



  • Eh, Python has its fair share of pain. Crap compatibility between versions? Weird, procedural-style methods (I have to take the "this" pointer as an argument??)

    Still, it's ok. It's one of my top languages.

    I doubt we are in the same city. However, from the looks of it, you live in Boston. I lived there several lifetimes ago.



  • It has some weirdness. I avoid 3.x, like the rest of the world. But the two environments I use have 2.4 and 2.7, which makes it very interesting.

    I'm originally from New England, but a left coaster now. one of the defense havens of Kalifornistan.



  • Ah, I don't actually work in defense, that was just an excuse to post something troll-y.

    I do, however, work for companies based in the Land of Fruits and Nuts. I do not live there, though.


  • :belt_onion:

    I could ignore the first line, if everything after it wasn't fucking horrendous. After seeing the other stuff, then going back to the first line, it looks pretty shittastic too.


  • Trolleybus Mechanic

    @Arantor said:

    No, PHP isn't entirely terrible. It's only mostly terrible and it is possible to write sane things in it.

    Y'know, that's one of the things that gets me wondering: PHP has been around for ages and yet it doesn't seem like anyone has developed much in the way of best practices, patterns and things never-to-do-under-any-circumstances.

    I mean, PHP is primarily used for web development and most of the time you're likely to be dealing with a relatively small number of standard problems (DB access, accepting input, display) that really should have been adequately solved by now. However, it seems to me that sensible solutions are drowning in a sea of downright insane ones - including (especially?) mature and well-known software. Why is this?


  • :belt_onion:

    @Kuro said:

    Is the problem here that he put echo inside Javascript and thats terrible if you do it a lot?

    That line really depends on the surrounding code to me. I've done some PHP into JS before, but generally try to consolidate it immediately into a js variable so you don't have inlined PH shit in the middle of your JS code. Then all you have to understand is the variable initializations and the rest stays the same.
    [code]
    var key = <?= json_encode($key) ?>;
    $('#'+key+'_colorpicker').farbtastic('#'+key);
    [/code]
    I'd also like to know why it is that the $key NEEDS to be in the JS there. Surely it was something the JS could have read from the DOM objects on its own? If you really, truly, legitimately have a whole shitload of PHP variables that you need to use in your JS and no other way to get at them, it might even be more sane to do something like this at the top of your script:
    [code]

    <script>var $phpGarbageAsJsObjectOrArrayDependingOnThePhpArrayIndexes = </script>

    [/code]



  • There are several frameworks out there which implement best practices for PHP: ZF2, Symfony, etc..

    I think PHP's problem is that it is easy, ubiquitous and the language was designed by idiots. So you get a lot of non-developers or crappy developers doing bad things in it and it reflects poorly on the platform. Truthfully, though, when you actually know how to use PHP effectively it's powerful. Which isn't to say it doesn't have flaws, like every other single language (perhaps with the exception of C#, which is nearly perfect.)



  • @morbiuswilters said:

    There are several frameworks out there which implement best practices for PHP: ZF2, Symfony, etc..

    That sounds like a problem, not a solution.



  • @chubertdev said:

    That sounds like a problem, not a solution.

    And the same thing doesn't apply to Python, Java, C#..? Good frameworks are a large part of making a successful language. Do you do C# without .NET? Java's a fucking hot mess, but Spring, et al makes it tolerable.

    Javascript? Yeah, raw JS is actually pretty rad, but you need a framework.



  • @GOG said:

    Y'know, that's one of the things that gets me wondering: PHP has been around for ages and yet it doesn't seem like anyone has developed much in the way of best practices, patterns and things never-to-do-under-any-circumstances.

    You are quite mistaken. 5-10 years ago that was true, but not anymore. The thing is, this standardization is coming from the developer community, not the PHP team itself. There is a number of excellent frameworks out there (e.g. Laravel), and the different framework development teams have banded together to see what can be done standards wise, and have already come up with a few good recommendations, known as PSRs.

    Also, there is this. This last one in particular is a great way to see what can be done with PHP these days, and what problems have been solved. It gets thrown at newbies all the time, or at people who have been away from PHP and are looking to see what they've been missing out on.

    Don't get me wrong, there's still a lot of cruft out there in terms of shitty code and shitty PHP programmers, but there is also a big, and growing, number of really good developers out there who write solid code riddled with best practices. In PHP, you can do OOP and TDD, there are great build systems and things like Vagrant support PHP out-of-the-box.

    @GOG said:

    I mean, PHP is primarily used for web development and most of the time you're likely to be dealing with a relatively small number of standard problems (DB access, accepting input, display) that really should have been adequately solved by now. However, it seems to me that sensible solutions are drowning in a sea of downright insane ones - including (especially?) mature and well-known software. Why is this?

    I don't know that that's true. If you pick a decent framework, all of those things will have good solutions that are present in the framework, and more, such as session encryption, CSRF prevention, caching, and templating. Folks who know what they're doing use them.

    And let's not forget that it's entirely possible to write really, really crappy code in any language, with any framework. I understand why PHP is often singled out, but it's not like writing an application riddled with spaghetti code that's full or SQL injection vulnerabilities is mathematically impossible in C#/.NET.



  • @toon said:

    Also, there is this. This last one in particular is a great way to see what can be done with PHP these days, and what problems have been solved. It gets thrown at newbies all the time, or at people who have been away from PHP and are looking to see what they've been missing out on.

    Thanks for that link. I'm theoretically still considered a PHP programmer, even if most of my experience is with old-style procedural code and forgotten ASP-wannabe frameworks. I should at least get up to date on practices if at any time I might be asked to do PHP...


  • Trolleybus Mechanic

    I should've perhaps phrased it differently.

    What I meant is that PHP is a mature language and hence should have a considerable body of typical ways to do things that you learn early on and most programmers in the language use naturally. Standard idioms, if you will. For all I know, this may be the case, but that's not the impression I'm getting when reading people who are much more familiar with the language than I am. Quite the opposite, it seems like there is a body of standard anti-patterns that everyone knows.

    Maybe it's a filter bubble, but it really does look like PHP attracts bad programming practices more than most languages and that these infect even high-profile projects in the language - again, I'm basing this on the opinions of people who know it better than I do. I'm just wondering why that is, given that these days good practices should be spreading virally, as it were.



  • @GOG said:

    given that these days good practices should be spreading virally, as it were.

    [citation needed]


  • Trolleybus Mechanic

    Explanation: if you hang out anywhere where other devs do (like here, for instance) you're going to hear a lot of "don't do this under any circumstances, 'coz bad things will happen".

    Ninja: back when I was starting out, you'd need to actually read books to find this stuff out.



  • I'm not sure I consider TDWTF the best guide of best practices. It's nice, sure, but lots of stupidity is perpetuated myah.

    PHP takes time to master. As does every good language. PHP has a lot of idiots using it, like every good language.

    I'm not even saying PHP is good, just that I can't deem it bad, compared to the rest of the language world.


  • Trolleybus Mechanic

    I'm not actually bashing PHP, though it may seem like that. I'm just genuinely surprised at the reputation it has. Sure, you can blame it on people who don't know what they're doing, but that leads us to ask: how come they ain't finding out what to do, in an age where information is easily disseminated? Or is it that idiots doing PHP are just more visible than those doing other languages?



  • I think it's partially because PHP has a lot of crufty bad things built-in which lead people astray.

    Also, it's kind of the entry-level server scripting language. You want a $1 /month web hosting account? It will support at least PHP. You start searching around for "how I learn how program?", PHP is the answer.

    Basically, it's taking over the niche VB filled so many years ago.


  • Trolleybus Mechanic

    That would have been my guess, but that doesn't really explain why major projects in the language (WordPress, for example) are being bashed for being downright terrible - which is what fascinates me. Is it an open source thing or a language thing? Or is it that people doing open source in PHP are less skilled - on average - than people doing open source in other languages? These are honest questions.


  • 🚽 Regular

    @morbiuswilters said:

    drone

    In my country we have our own drone now, look at it go!

    http://www.youtube.com/watch?v=ShUc3znAzqY#t=23


  • BINNED

    @morbiuswilters said:

    And the same thing doesn't apply to Python, Java, C#..? Good frameworks are a large part of making a successful language. Do you do C# without .NET? Java's a fucking hot mess, but Spring, et al makes it tolerable.

    I don't do C++ without Qt any more. I have the same argument as morbs has for PHP there. You know all those common complaints about memory management, casting shit around and similar in C++? Yeah, use Qt and worry no more.

    And no, it's not just a graphic toolkit like GTK. It's a full framework capable of doing whatever you damned please with just a few lines of code these days. Networking? Check. Easy multithreading? Check. Websocket support? Check. Multiplatform? Check. Automatic memory management? Just inherit from QObject and worry no more.



  • What platforms support Qt? You've peaked my interest.


  • Discourse touched me in a no-no place

    @SpoofedEx said:

    Don't use 4images...

    You not read @Keith's link then?


  • BINNED

    @toon said:

    What platforms support Qt? You've peaked my interest.

    Windows, Linux, Mac, Android (compiles into native code, no Java wrappers), iOS, WinRT is in beta I think, embedded Linux...

    From what I gather it's used in embedded Linux environments a lot. Also, Adobe's tools are Qt, or so I've been told.

    Full info: http://qt-project.org/doc/qt-5/supported-platforms.html

    I'm working on a Linux service written in Qt for work, dabble with desktop programming for Linux / Windows in spare time. So far, never had a problem in cross-compiling stuff.

    And using Qt Quick you can hook up identical backend code to various UIs written in QML for mobile platforms. You can even cross-compile desktop apps to mobile if you use QML for frontend on desktop (there are components that pick up your system theme so it looks native).



  • @morbiuswilters said:

    I think it's partially because PHP has a lot of crufty bad things built-in which lead people astray.

    Also there are lots of tutorials written by people who don't what they're doing. When the bad and outdated tutorials vastly outnumber the good ones, misinformation spreads. I'm sure that's related to the low barrier to entry.



  • Yup.

    PHP has many faults, and they are slowly working the worst ones out of the language but the install base and dependence on bad code really does not help.

    But well written PHP is not in a different ballpark to well-written <any other language>



  • Is it possible to write websites in Python without some WTF-ery of difficult-to-install-and-configure packages that haven't had their Linux docs updated since 1812? I rather like Python, if it was as simple to set up and deploy as PHP I'd look into it.



  • Python on Windows has been a nightmare. It's a bit better on *nix, but still not great.



  • @mott555 said:

    Is it possible to write websites in Python without some WTF-ery of difficult-to-install-and-configure packages that haven't had their Linux docs updated since 1812? I rather like Python, if it was as simple to set up and deploy as PHP I'd look into it.

    Well, many frameworks nowadays do ship with a WSGI host for dev/test purposes (CherryPy, which is what I have used, has cherryd for this job, as an example). However, I still haven't figured out how to take a WSGI app and make it auto-deployable to $insert-random-host-here though!

    Or, in other words: there are so many Python web frameworks out there that getting a One True Deployment Mechanism might be impossible, even with the relative standardization provided by WSGI.

    (On the other hand: if you can live with using your framework's app server instead of dropping into an existing one, simply having an egg or wheel that can be dropped into a virtualenv might just be the best way to go; that way, pip/setuptools/distribute can take care of 90% of the gory bits once you get the hang of setup.py, and you have your own isolated playground re: Python modules, even). In fact, virtualenv is one of the things that Python gets right that many languages just don't even think about.

    Now if you want a Python WTF: they still haven't quite figured out how to get Unicode stdio in the Windows console yet. (It's possible, but you need to call Windows APIs directly as MSVCRT is buggy as heck in this dept.; AFAICT, the current snag is having to do a bunch of faffing about with the way Python lets you assign to sys.stdin/sys.stdout/sys.stderr.)



  • @toon said:

    You've peaked my interest.

    Piqued! Piqued!


Log in to reply