PHP
Article

PHP Tips, Resources and Best Practices for 2015

By Bruno Skvorc

PHP has had many reputations over the years, but being insecure as a language never really was one of them.

The core team, all its faults notwithstanding, is rather quick in pouncing on all security matters, and updating PHP to the latest version will often allay all worries. But the end users, such as we are, tend to mess things up. We don’t update, we use outdated packages or packages with holes in them we’re not aware of, we use ancient extensions… we expose ourselves to risk in some truly creative ways.

Tips, Resources and Best Practices

Let’s start 2015 off right, shall we? This post will list important resources you should have in your brain/toolbelt before building anything with PHP in 2015. I’ll do my best to keep this post up to date, so it stays relevant indefinitely, but, like I said, I’ll need your help.

Keep your PHP up to date

When I wrote about the cancer that is legacy code, I focused on application code. I still firmly believe that you should never develop for the lowest common denominator, else you risk becoming the very thing that’s holding your language’s progress back. That’s not the focus of this section, though. Recently, a new version related discussion ensued.

CodeIgniter and WordPress are sticking with PHP 5.2 support (a version that’s been dead for four years now and shouldn’t exist on anyone’s server), and Anthony Ferrara responded in his blog post. Before you read this section any further, I implore you to read that post first. It’s important.

What that post accomplished was getting some people too lazy to upgrade riled up.

They argued for legacy support without considering the damage they’re doing to the PHP ecosystem. Anthony wrote another post in which he further explains his stances, and finished up with yet another post taking apart installation percentages of old PHP versions across the web, comparing them to the stability list to find out how many servers running PHP out there are insecure by default and hackable – today. The results are frightening to say the least.

If you’re developing something and are running anything but the latest major version of PHP, I urge you to give these posts a thorough read. If your client insists on host X or version Y for whatever reason, refer them to these posts, educate them, and help them see the error of their ways – teach them about the vulnerabilities they’re introducing to their project, and tell them about the horrors that can happen if they don’t act before it’s too late. Upgrading your PHP’s version is not something you should file under “we can do that later”. Do it now, and do it often.

Avoid outdated hosts

Inspired by the aforementioned discussions, Phil Sturgeon compiled a table of current PHP versions supported by various hosts. You can find it at PhpVersions.info or if you’d like to contribute and add some missing values, on Github.

I recommend you steer clear of all shared hosting in general – there are extremely cheap VPS providers out there now, like DigitalOcean (feel free to check them out via my ref link for a leg up).

Don’t be these guys. It starts out innocent and simple, but when you end up having to lend out your partner while doing someone else’s laundry, it stops being fun.

When opting for a VPS, other than saving you from sharing an environment with everyone else or being susceptible to the instability of a system as introduced by someone else, setting up your own server from scratch is a fun and rewarding experience you should be familiar with anyway. Besides, you can see on the list that barely anyone has the latest PHP version as the default one – why settle for anything but the latest software when starting a new project?

Adopt HTTPS

Encryption is crazy important today. Not just as a means of defending yourself from government snooping, but also as a way to make sure your clients and website visitors are protected as well and aren’t leaking any personal data. With advocates such as Ilya Grigorik and his pitches for TLS to Google announcing it would favor websites with HTTPS in search results, there’s no question about the ever increasing importance of HTTPS, even for simple websites.

While there are workarounds to getting HTTPS everywhere, one shouldn’t rely on those – it’s our responsibility as web developers to improve the web at large. HTTPS is not directly related to PHP, but whenever you’re starting a new PHP project it’s generally easier to set up your server to use HTTPS before you start coding, rather than in the middle of a project. To help you get through this often cryptic, daunting and discouraging task, (at least until Let’s Encrypt is out) Chris Palmer put together this Google Doc.

Secure your PHP

Don’t be these guys.

Follow best practices in password protection, generation, encryption and authentication. Read books and use packages like those suggested on the SecuringPHP site.

Stay on the Right Way

PHP The Right Way is responsible for improving the life of many a PHP project out there. In book form or digital, PTRW is an indispensable resource for making sure you’re fit to handle the challenges of modern app development. If you feel like it’s missing something or just want to contribute with typo corrections or alternative resources and guides, feel free to do so via Github.

Avoid Bad Packages

Almost two years ago, Fabien Potencier of Symfony fame announced the creation of a list of vulnerable packages for PHP. A year and a half later, this became standard part of Symfony and was turned into open source public domain property. You could now post your composer.lock file to their API or the web interface, or even the CLI tool, and it would check your project for vulnerabilities. However, this still required one step from the end users, and we’re lazy, lazy people.

Enter Roave team, the laziest of us. They made a security-advisories package which uses this database of known vulnerabilities. As Marco Pivetta explains in his blog post, you require it in your project like any other package, but instead of downloading anything, the package serves as a meta-package, not downloading anything and instead checking for whether the bad versions are required in your project. It will warn you and prevent even the attempt to download those packages, saving you not only a checking step, but a step that includes deleting them as well.

I urge everyone doing PHP development to include this in their projects. By jointly attacking the common vectors of insecurity, we’ll be one step closer to eradicating security holes on a large scale.

Dodge common mistakes

We’ve compiled lists of common mistakes before. Read the following posts to learn what to avoid:

By keeping these in mind, you’ll save yourself a world of trouble and major headaches down the road.

Virtualization

Use Vagrant! Even PTRW says so.

Vagrant helps you run cloned environments in small, headless virtual machines that forward requests to ports inside the machine, letting you use your host’s browser and your host’s IDE without interference. Want to nest a virtual machine inside a virtual machine? You can do that too, and it’s all completely safe! We’ve got a bunch of Vagrant tutorials and explanations under the Vagrant tag, so if you’re confused about the technology, read up.

Here at SitePoint, we have an officially endorsed fork of the Homestead Vagrant box (prepared by Laravel’s Taylor Otwell, but compatible with any framework and PHP application) called Homestead Improved. It’s runnable in under five minutes and you’ll have a completely encapsulated PHP environment to play in – with no fear of messing up your host OS or other projects. Made a mistake? Just destroy, rebuild, and you’re back where you started (with zero code lost) in a minute!

Note that we’re using this box in all our tutorials, so getting familiar with it now will both save you some time in the long run, and help you follow along with everything we do with great ease, not to mention the effect it’ll have on your local development environment.

Blackfire.io

Blackfire.io is a service from SensioLabs, the guys in charge of the Symfony framework and all its related technologies. It’s a transparent and low-overhead profiler able to analyze your code and alert you to issues with everything from application logic flow to interactions with the DB engines and even the cache layer. Blackfire is already installed in the Homestead Improved box mentioned above, so if you use our box or the original Homestead, you’re all set!

Catch problems before they throw a wrench into production! More detailed tutorials regarding Blackfire are coming soon!

Conclusion

We looked at some important links and resources for starting off your 2015 PHP projects properly, with performance and safety in mind. If you’re already using all these approaches, good for you – you can help us spread the word. Tell your friends and developer circles about it, direct them here, point the newbies who ask you how to get started our way and refer to the specific links in the post whenever someone tells you that legacy code should be supported and old PHP versions are fine. Send them here, and we’ll rough’em up!

Disagree with any of these? Would you add some critical resources that the resources we’ve linked to don’t already mention? Let us know – I’ll make sure the list gets updated!

Comments
Michael_Morris

Only day 2 of the new year and the mis-statement of the year may have been made. PHP is infamous for being insecure. The core has improved, I'll grant that, but the community surrounding it still doesn't take the issue seriously. That's not unique to PHP, but it seems worse among PHP progammers. The language itself does little to nothing to help users avoid these problems - loose datatyping is a hacker's dream for causing all sorts of havoc. It wouldn't be so bad if you could turn it off.

I can't be too critical of PHP - it does pay my bills - but don't call it something it never has been - secure. It's not - you have to watch it and the programs ran using it like a hawk.

Pepster

There's to many PHP legacy tutorials out there on the internet, every day you see people who are new to PHP ask for help on script for they are learning PHP for the first time and found this tutorial on the net or it's obvious they had for I spot is msyql instead of mysqli or PDO. Then you explain to them that mysql is obsolete and that you should choose one of the two alternatives. You get one of two responses.
First response - "Oh I didn't know that, Thanks for pointing that out"
Second response (This one irks me to no end) - "Oh I know that, but I just want to get my script to run. I'll go back later on and change it when I have the time".

I see that second reponse a lot and sometimes you get even a worse response than that, something like "I don't care, I just want to get my script to work". The later group of people is a lost cause and the ones who say they will go back when they have the time, I doubt that they ever will. It is not just that the make for PHP insecurities, for it's other aspects of programming in PHP that make it insecure. A lot of people have this way of thinking - "If it is on the internet, it must be true" mentality.

I still remember what it was like when I was new to PHP and spent long hours on a script only to ask help on it to get the reply - "You best to throw that code in the trash and start over for that has more security holes in it than Swiss cheese does". The first inclination is to get defensive about it, but after a cooling of period you realize that the person was only trying to steer you in the right direction. It's better to get a better grasp of PHP by doing it the right way the first time and I have learn before tackling something new in PHP to ask if I starting off the right way. Thus, hopefully avoiding spending needless hours on PHP code that is a pile of junk. That is my opinion why PHP can have a bad reputation, for there still a lot of legacy code still out there on the internet masquerading as helpful tutorials.

felgall

No it isn't - as the article states, many people write insecure programs using PHP but PHP itself is as secure as most other programming languages.

There is a huge difference between insecurity being built into the language and people simply writing insecure code using a secure language.

One of the biggest problems is that almost all books and sites teaching PHP do not include the code to make their example scripts secure in order to save space and to make the code being discussed easier to see. The people learning mostly assume that the code they have been taught is sufficient and so they leave out the other 80% of the code they should be writing that handles the security aspects.

There are books available on PHP security that specifically teach you how to write the code in a secure manner and if that approach is followed then PHP is as secure as any programming language can be.

Michael_Morris

Now yes. Back in the days of register globals et al, not so much.

Mittineague

I think a main cause for so much poor PHP code is

OK, maybe some don't copy-paste, it works, great! next. But I fear many do.

felgall

That still has nothing to do with how secure PHP itself is. Sure many programs written in PHP are insecure because they omitted all of the validation and other security features but the article is referring to PHP itself as being secure - the code used to write PHP does include all the security features - you can write insecure programs in any language.

There are far more amateur coders writing in PHP than in most other programming languages - that's why so many programs written in PHP are insecure. The insecurity is in the way they write their code - it isn't built into PHP and those who know how to program properly can write programs in PHP that are just as secure as programs written in other languages.

cpradio

Exactly. I agree with that entirely. I've seen some really really insecure .NET applications in my life time. I've fixed a lot of insecure .NET applications. Same with Ruby, Python, Perl, PHP. It doesn't mean the language itself is insecure, it simply means the programmer didn't do their due diligence.

However. It can be proven that PHP among other languages (.NET, Ruby) do have security holes within the language itself. That's what patches and updated versions are for though...

Mittineague

I imagine that the fact that PHP is so ubiquitous plays a major part in why it's potential security flaws come to light more so than other languages

felgall

PHP hasn't had noticeably more security holes in the language itself than any other popular programming language though.

swader

Every kitchen has a knife.
You can use it to poke out someone's eye, to cut your veins, to damage your household.
Why you're allowed to have it at home is because a basic knowledge of its use is assumed.

If given basic security training in PHP via the resources linked in the original article, one becomes basically proficient in PHP security measures.

Much like you don't let a child stab itself to find out knives are dangerous, so shouldn't you let a rookie developer sabotage themselves with bad, outdated resources. As a PHP developer, it is on you not only to develop, but to educate those around you and to help spread good practices by means of, at the very least, referring them to proper sources.

Like the others said - every language is as insecure as those using it make it.

timoh

That's not actually the case.

During 2014, PHP got 32 CVE IDs assigned, Ruby got 3 and Python 6.

While most of the PHP's bad reputation comes (as mentioned here) from bad programming habits, bad code examples, bad books and so on, it is a fact that the PHP language itself has had more vulnerabilities than, say Ruby lang and Python. So based on that, I can understand why some might want to call PHP "insecure language" (it is not as "with no foundation" saying as many PHP devs may at first glance think).

felgall

When you compare the number of people actually using each of those languages (and therefore the need to actually find and fix security holes) that actually makes PHP the most secure of those three languages s there was far more than ten times the incentive to find security holes in PHP.

Windows always has far more security holes found and fixed each year than any of the alternative operating systems which is why Windows is many times as secure as ANY of their competitors.

All software has security holes - the more that are found and fixed the more secure that software is.

SpacePhoenix

It's probably going to take the removal of the "legacy" mysql_* functions by hosting companies from their servers before some people finally migrate over, tbh it's about time that hosts started to remove the mysql_* extension from their servers as people and companies have had enough time to get their code migrated over to using the mysqli_* extension or PDO (my personal preference is to use PDO).

The other thing that I see is where people are letting user-submitted data near the database without sanitizing it and at the very minimum escaping it, tbqf the use of prepared statements should really be the norm now.

I know that some of my own scripts need more sanitizing added to them, sometimes I see scripts where there's been no attempt at sanitizing the user-submitted data.

timoh

I don't think it is that simple to justify that "PHP is the most secure of them". All of the three (PHP, Ruby Python) are "mainstream" languages with huge user bases. While PHP has the largest user base, it doesn't mean that Python or Ruby lacks security audits or research, or that research towards PHP is superior compared to Python or Ruby research.

And it is not only about plain user base size. Some other important factors are bounties offered/paid, importance of the victim, and quality of the audits.

I'm not saying one could justify which language is the "most secure" just by looking assigned CVE IDs, but I think, in this case, it gives some view.

Also, it is important to acknowledge that while software gets more secure immediately a vulnerability has been patched, but the other side is that the exact same software has been insecure as long as the point when the vulnerability was introduced in the code to the point it was fixed and deployed to the "end user" (which could be quite a long times).

Raju_Gautam

I totally agreed with the fact that "PHP itself isn't insecure", it depends on how you code in it. I have written most vulnerable code in my life and rewritten quite couple of times. No one cannot bet that PHP doesn't/didn't have any flaws/security holes but they are found, reported and fixed quite soon after its release because it is quite popular and holes are found on time.

If someone doesn't upgrade the fixes on time then that's not PHP's problem ! Be updated and write code securely, otherwise your child can get the knife and cut anything.

heera_sheikh77

No language is responsible for insecure application but the developer who codes it and doesn't take care of it. generally speaking, don't blame others for your incapability. Is there any proof that, hackers only hacks or hacked sites or application written using PHP but not written in other language? Probably not then stop blaming any language.

freakyrag

That's true. But some languages make it harder and some make it easier to write insecure code. PHP is just so shockingly inconsistent with a lot of features added on top later in its life that it really makes it very easy to write shitty code. Add to that an abundance of very outdated tutorials and books and virtually unlimited number of inexperienced developers giving poor advice and it becomes a big problem.

felgall

As those people progress to writing code in other languages the number of improperly written applications in those other languages will increase. The issue is that so many people write PHP without having learnt how to write programs properly in the first place and as you say, these people without any idea of how to write proper programs then advise others in how they too can write insecure garbage.

Being able to code properly is independent of the programming language used. Unfortunately since the portion of the code to make it secure is generally around 75% of the total code and this part of the code is not necessary for working examples it usually gets left out of most books teaching programming. Experienced programmers know this and will add all the extra code needed but many newbies never get beyond writing example code never intended for a live environment.

PHP actually makes it relatively easy to implement most of the security needed. All you need to do is to avoid moving $POST and $GET values (etc) out of those arrays without validating the values first. That takes care of about 50% of the security issues that most newbie code has without even applying any security measures (since you need to do that to prevent junk input anyway).

TomB

I totally agree with your comments on PHP versions. Projects should not support PHP versions that are no longer officially supported by PHP. It dissuades people from upgrading and as you say, damages the entire ecosystem.

Once official PHP support for a version is dropped, so should project support.

Michael_Morris

I think that minor versions of projects (or major versions of software with rapid dev cycles) should start with a minimum of whatever PHP version is oldest current and stay with that for its life cycle. Hence if Drupal 8 where to go gold today it would support PHP 5.5 until 8.1 is released.

swader

I think there's equal chance of people having 5.5 and 5.6 installed - both suffer from a lack of exposure. I'd go with 5.6 off the bat.

Michael_Morris

5.5 is still better than the 5.2 floor more than a few projects are holding onto (Wordpress...)

antwar1986

very usefull, thanks for the informations here

felgall

The current version of WordPress may still run on 5.2 but it is intended to be run on 5.5.

On 5.5 it uses the mysqli database interface instead of the mysql one - as you can easily find out by turning the mysql interface off.

peter_indexed

Unfortunately many WP installations is on shared hosting where they are probably affraid of upgrading.

Its crazy that only 10% of all WP installations is 4.1 and 32% of all installations is running on PHP5.2

Not everyonly is updating like the rest of us:)

felgall

It is all of the other sites sharing on the same server who need to be afraid of those not upgrading as not upgrading produces a potential security hole on the server.

No wonder WordPress has such a bad reputation if 90% of installs are not up to date.

peter_indexed

I used to work at a web agency who did'nt care about upgrading unless the customer directly paid for the upgrade. So instead we used alot of time to fixed those sites which got hacked WITHOUT the customer paying.

I hope thats not the attitude elsewhere.

unikainfocom

Hi,

very usefull Thanks for the share

frivgood

information that you share exactly, it makes sense, and I've used it successfully, thank you for sharing

s_molinari

Amen!

It doesn't matter what developer you are, this is a general "developer commandment" I believe in.

A lot of times too, especially helping on the Internet, you might try and help someone, only to learn, you aren't quite right yourself. So you also end up learning too. I think, as a developer, being humble in knowing that I don't know everything, is also important. It is actually another commandment.

"Thou shall always be humble and never think thy knowledge is all encompassing!"

The other commandment from Bruno could be

"Thou shall always help the lesser knowing developer".

innocent

Scott

ejoni

cool thank you!

Aqib_Qureshi

It sounds very interesting!
i like the post very much keep it up
Yah this forum is making a dfference. I love it.

KevinOBrien

You can not directly criticize PHP. PHP is an open source language and you can learn form the internet, there are thousand of tutorials are available. You can make PHP secure by powerful scripting.

Marlena13

Very useful site, thanks everyone, glad to be a member

Jadengeorge

Good article with link to read and learn more on PHP. I started with w3school and it serves to be the simple and easy PHP guide.

Killian74

PHP is a very popular language, because it appears to be simple to learn. There is a lot of tutorials out there, but (as already said) most of them are outdated or lack security considerations.

I think, the major problem is not the core. The main problem are the old versions on small servers running, because the admins are big hosting companies and they do not want to explain to the user why a specific script can not run.

A lot of PHP programmers do a lot of coding in their free time and security has always been a pain in the a**. You can break things really fast, if you don't know what you do in the update process.

PHP (like other server technology) is open to attacks from all over the world, this fact must be emphasized on the main PHP help pages.

To fix this, we have to:

  • provide best practices for novices (escape input / output, check input boundaries etc.)
  • provide anti-patterns
  • encourage big frameworks to move to newer PHP versions and drop old version support
Jefferson_Altamirano

Thanks for giving me this guide, this could help me from my future PHP programming smile

Oliver2

Well I have also started learning php during these week and I must say I've been really enjoying learning it.

My favorite place for php discussion is pingx.net

s_molinari

Pingx.net isn't a discussion platform, but rather an archive for IRC discussions.

Scott

WardBradley

If you are an amatour, you should use easier to learn PHP, for instance Yii
You can read more about its benefits comparing to other PHP in this article
http://webinerds.com/seven-cmss-consider-designing-website/
When you become more aware of how it works you can try to begin your work with Symphony 2
Some tutorial
http://code.tutsplus.com/tutorials/symfony-2-the-basics--net-37015

Guruofmayhar

Updating the PHP is a far better way, other than weeping over the split milk. If you are updating the PHP regularly then you will get the better results and if you are not doing so then you surely will face the brunt of your slackness.

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in PHP, once a week, for free.