PHP Security Guide: How to save your PHP website?Advance Idea InfotechBlockedUnblockFollowFollowingMay 7Damn, but security is hard.
It’s not always obvious what needs doing, and the payoffs of good security are at best obscure.
You should build your web apps protective enough to have no security issues or loopholes, thus eradicating the possibility of any malicious attack.
In most cases, the developers must take the responsibility and put in every possible effort to identify the vulnerabilities and propose solutions, if any to address the issues prevailing in the apps.
PHP is a popular language for web development.
It is so popular that In some cases companies do run few bounty programs in which they invite different security experts to analyze their application from the core and suggest critical PHP security best practices for it.
This security checklist aims to give developers a list of PHP security best practices they can follow to help improve the security of their code.
Table of ContentSecurity Issues in PHP CMSWhat This PHP Security Tutorial Contains?Update PHP RegularlySet open_basedirCross-site scripting (XSS)SQL Injection AttacksCross site request forgery XSRF/CSRFSession HijackingHide Files from the BrowserSecurely Upload FilesUse SSL Certificates For HTTPSDeploy PHP Apps on CloudsDocument Root SetupLog all Errors and Hide in ProductionDo not send sensitive information in&headersWrapping Up!PHP is the most criticized scripting language when it comes to security.
A major chunk of developers and QA experts think PHP has no robust techniques to secure applications.
The verdict has some ground too because PHP is the oldest and widely used language for web app development.
But for a long time since PHP 5.
6, we haven’t seen any major updates regarding security and hence the language faces some security issues.
Security Issues in PHP CMSPopular CMS like WordPress, Joomla, Magento, and Drupal are built in PHP and according to Sucuri, most of the vulnerabilities in PHP CMS came to light during the year 2017:WordPress security issues rose from 74% in 2016 Q3 to 83% in 2017.
Joomla security issues have dropped from 17% in 2016 Q3 to 13.
1% in 2017.
Magento security issues rose marginally from 6% in Q3 2016 to 6.
5% in 2017.
Drupal security issues dropped slightly from 2% in Q3 2016 to 1.
6% in 2017.
The current situation is not good enough, but thanks to open source contributors, who are trying hard to overcome the problems and we have seen some drastic changes in PHP of late.
x was launched last year with various updates and fixes.
The best thing about PHP 7.
x relates to the security upgradations which truly revamped the security protocol of the language.
What This PHP Security Tutorial Contains?We’ve been working on PHP security and performance issues for a very long time, being highly active in the PHP community asking top developers about the tips and tricks they are using in their live projects.
Therefore, the main aim of this PHP security tutorial is to make you aware about the best practices for security in PHP web applications.
We will be defining the the following problems and mentioning possible solutions for them.
Update PHP RegularlyCross site scripting (XSS)SQL Injection AttacksCross site request forgery XSRF/CSRFSession HijackingHide Files from the BrowserSecurely Upload FilesUse SSL Certificates For HTTPsDeploy PHP Apps on CloudsUpdate PHP RegularlyRight now, the most stable and latest version of PHP available is PHP 7.
We recommend that you must update your PHP application to this new one.
If you are still using PHP 5.
6 then you will be having a lot of deprecations while upgrading PHP apps.
You will also need to update your code and change some functional logics like password hashing etc.
There are also some tools available to check the deprecation of your code and help you in migrating those.
We have listed some tools below:PHP 7 Compatibility CheckerPHP 7 MARPhanIf you are using PHPStorm then you can use PHP 7 Compatibility Inspection, that will show you which code will cause you issues.
Set open_basedirThe open_basedir directive limits the files that PHP can access to the filesystem from the open_basedir directory and downward.
No files or directories outside of that directory can be accessed.
That way, if malicious users attempt to access sensitive files, such as /etc/passwd, access will be denied.
Read more:open_basedir configuration directivePHP Filesystem SecurityIsolated Execution Environments by DigitalOceanCross-site scripting (XSS)Cross site scripting is a type of malicious web attack in which an external script is injected into the website’s code or output.
The attacker can send infected code to the end user while browser can not identify it as a trusted script.
This attack occurs mostly on the places where user has the ability to input and submit data.
The attack can access cookies, sessions and other sensitive information about the browser.
Let’s look at the example of a GET request which is sending some data through URL:You can figure out this attack by using htmlspecialchars.
Also by using ENT_QUOTES, you can escape single and double quotes.
Meanwhile, XSS attacks can also execute via attributes, encoded URI schemes and code encoding.
SQL Injection AttacksThe SQL injection is the most common attack in PHP scripting.
A single query can compromise the whole application.
In SQL injection attack, the attacker tries to alter the data you are passing via queries.
Suppose you are directly processing user data in SQL queries, and suddenly, an anonymous attacker secretly uses different characters to bypass it.
See the below-mentioned SQL query:The $username can contain altered data which can damage the database including deleting the whole database in the blink of an eye.
So, what’s the solution?.PDO.
we recommend that you always use prepared statements.
PDO helps you in securing SQL queries.
Let’s look at another example in which GET data is sent through URL: http://example.
php?id=1 OR id=2;The connection between the database and application is made with the below statement:You can select username based on the above ID but wait!.Here SQL code ‘GET data’ gets injected in your query.
Be careful to avoid such coding and use prepared statements instead:Now you can avoid the above SQL injection possibility by usingAlso, a good practice is to use ORM like doctrine or eloquent, as there is the least possibility of injecting SQL queries in them.
Cross site request forgery XSRF/CSRFThe CSRF attack is quite different to XSS attacks.
In CSRF attack, the end user can perform unwanted actions on the authenticated websites and can transfer malicious commands to the site to execute any undesirable action.
CSRF can’t read the request data and mostly targets the state changing request by sending any link or altered data in HTML tags.
It can force the user to perform state changing requests like transferring funds, changing their email addresses etc.
Let’s see this URL in which GET requests is sending money to another account:Now if someone wants to exploit the web application he/she will change the URL with name and amount like thisNow this URL can be sent via email in any file, Image etc and the attacker might ask you to download the file or click on the image.
And as soon as you do that, you instantly end up with sending huge amount of money you never know about.
Session HijackingSession hijacking is a particular type of malicious web attack in which the attacker secretly steals the session ID of the user.
That session ID is sent to the server where the associated $_SESSION array validates its storage in the stack and grants access to the application.
Session hijacking is possible through an XSS attack or when someone gains access to the folder on a server where the session data is stored.
To prevent session hijacking always bind sessions to your IP address to:Watch for it when working on localhost as it doesn’t provide you the exact IP but :::1 or :::127 type values.
You should invalidate (unset cookie, unset session storage, remove traces) session quickly whenever a violation occurs and should always try not to expose IDs under any circumstances.
For cookies, the best practice is to never use serialize data stored in a cookie.
Hackers can manipulate cookies easily, resulting in adding variables to your scope.
Safely delete the cookies like this:The first line of the code ensures that cookie expires in browser, the second line depicts the standard way of removing a cookie (thus you can’t store false in a cookie).
The third line removes the cookie from your script.
Hide Files from the BrowserIf you have used micro-frameworks of PHP, then you must have seen the specific directory structure which ensures the placement of files properly.
Frameworks allow to have different files like controllers, models, configuration file(.
yaml) etc in that directory, but most of the time browser doesn’t process all the files, yet they are available to see in the browser.
To resolve this issue, you must not place your files in the root directory but in a public folder so that they are not accessible all the time in browser.
Look at the directory structure of the Slim framework below:Securely Upload FilesFile uploading is a necessary part of any user data processing application.
But remember at some points, files are also used for XSS attacks as we have already explained above in the article.
Returning to the basics, always use the POST request in the form and declare the property enctype=”multipart/form-data” in <form> tag.
Then validate the file type using finfo class like this:Developers can create their own custom and ultra-secure file validation rules, but some frameworks like Laravel, Symfony and codeigniter already have pre-defined methods to validate file types.
Let’s look at another example.
The HTML of form should be like this:And upload.
php contains the following code:Properly declaring the UPLOAD_ERR and basename() may prevent directory traversal attacks, but few other validations — like file size, file rename and store uploaded files in private location — are also required to strengthen the security of the applications.
Use SSL Certificates For HTTPSAll the modern browsers like Google Chrome, Opera, Firefox and others, recommend to use HTTPS protocol for web applications.
HTTPs provides a secured and encrypted accessing channel for untrusted sites.
You must include HTTPS by installing SSL certificate into your website.
It also strengthens your web applications against XSS attacks and prevents the hackers to read transported data using codes.
Deploy PHP Apps on CloudsHosting is the final and paramount step for any web application, as you always create the project on local PHP servers and deploy them on live servers which offer either shared, cloud or dedicated hosting.
We always recommend to use cloud hosting like DigitalOcean, Linode, AWS.
They are fast, safe and secure for any kind of website and application.
They always provide secured layer to prevent DDOS, Brute force and phishing attacks which are highly detrimental for web applications.
To deploy your PHP project on cloud servers, you must have good Linux skills to create powerful web stacks like LAMP or LEMP, which often costs you time and budget for Linux professionals.
Instead, Advance Idea Infotech managed PHP and MySQL hosting platform provides you the easy way to deploy servers with Thunderstack within few clicks on the above-mentioned cloud providers.
The Thunderstack helps your PHP application to be completely secured from various malicious attacks and guarantees optimized performance.
Document Root SetupThe document root for PHP applications on any server must be set to var/www/html so that users can access your website via the browser.
But in some cases, when you are developing APIs with frameworks like Laravel, Symfony, and Slim, you need to update the webroot to/public folder.
/public serves the output of application similar to simple PHP website with index.
The purpose to set the webroot to var/www/html/public is to hide the sensitive files like .
htaccess and .
env which contain the environment javariables and credentials of database, mail, payment APIs.
Also, frameworks like Laravel, Symfony recommend to not move all of your files to root folder, instead creating a nice directory structure to save related files like view, models and controllers is a more reasonable approach.
Log all Errors and Hide in ProductionOnce you have developed the website and deployed on live server.
The first thing you must do is disable the display of errors, because hackers might get same valuable information from the errors.
Set this parameter in your php.
ini file:Now, after making display off, log all the errors to a specific file for future needs:Obviously, you can change file name as you want.
Do not send sensitive information in headersBy default PHP will set his version number in the HTTP headers.
Some frameworks may do the same as well.
Read more:Hide PHP and Apache informations from HTTP headersWrapping Up!Well, The PHP security best practices is a very vast topic.
Developers from around the world tend to develop different use cases to secure web apps.
In this article, we have covered basic PHP security issues, to help you understand how to secure your PHP projects from different malicious attacks.
We’ll also write about few more PHP security tips and tricks in the future as well.