Laravel Security Best Practices – To Secure Your PHP Apps

PHP is a very popular web application development language and the best part is that it’s open-source. But with this comes the risk of security breaches and vulnerabilities in your application. In this post, we are going to discuss Laravel Security Best Practices and how you can secure your LAMP apps.

9 mins read
August 13, 2021
Getting into an unprotected platform isn’t a big deal nowadays, at least for hackers. The first time I experienced this was when I was in my coding school and one of my clients called me that there’s something wrong with this website. Actually, his website was suddenly taking a long time to load. When I got back on my computer to dig into this issue, I found that the hacker used an SQL injection and injected a <script> tag into the code. And when the user opens a website URL, it would take him to a fraudulent or malware website.

It was the first time I felt that hurdles like these can appear out of the blue and regardless of the size of a website, it can be a proper target for a hacker to misuse it. It was 10 years ago. After that, I placed web security as the topmost priority before developing any projects. It’s true that absolute website security is a myth because one over another high-profile hackers are always looking at their next targets. But there are a few things that you can do to build up the defenses of your website.

OWASP & Laravel

OWASP is known as – Open Web Application Security Project. This is a non-profit organization that helps aware individuals and business entities about the significance of web application security. It rolled out a standard awareness guide that explains the top 10 critical touchpoints of a website’s security.

Laravel is one of the best PHP frameworks that the world has ever seen. I have been working on it for a few years for both small to large-scale business projects. Most of these projects were highly sensitive and looked out for an extensive data and website security element. And thanks to Laravel, a developer gets all these security features handy. Here is the list of top OWASP security measures to help strengthen the security of your PHP projects on the Laravel platform.

Broken Authentication

Broken authentication is a common type of attack nowadays. However, you have a few strategies handy to counter it.

  • Using CAPTCHA on all the brute-force prone endpoints is always a good idea. The areas combined in this are: forgot password forms, registration, and login forms. CAPTCHA is good for stopping auto-generated web attacks. You can use Google’s reCaptcha if you don’t have time to develop your own CAPTCHA.
  • If your login attempts have no limit then consider limiting it. It provides a truly awesome protection layer. To throttle requests, use Laravel’s middleware.
  • Multi-layer authentication again adds an almost impenetrable level of security to your website. These can either be an OTP, a two-factor authentication, a QR code, email, or even SMS.
  • To secure your sessions, send them over with HTTPS only. Also, enable the ‘secure’ setting in your ‘session.php’ file.
Broken Authentication
To help the authentication process work properly, Laravel makes use of ‘Providers’ and ‘Guards’. It reduces the developer’s work significantly as he only needs to add databases, controllers, and models. If everything is working alright, Laravel features links to the app on its own.

To log a user into your application, you may use the Auth::attempt method

Laravel’s authentication services are accessed via the Auth facade, so make sure you import the Auth facade at the top of the class.

if (Auth::attempt (array(’email’ => $email, ‘password’ => $password), true))
      //The user is being remembered…

SQL Injection

Hackers mostly try an attempt to gain access to the information system through SQL injection attacks and then insert malicious SQL statements into form fields or other injection points to get unauthorized access to the database and use it for their profit. This is how they get access to the vulnerable database and get a chance to attack the underlying system.

These Injections are generally used by hackers to collect vital customer information like contact details, important credentials, or even debit/credit card details. The worst part is, with these attacks they may even control the database server and the operating system and exploit your web security vulnerabilities to control your critical business information like product price.

To protect a PHP project against SQL injection attacks, the Laravel query builder makes use of PDO parameter binding. Once this parameter is bound, the developer doesn’t have to secure the values being passed as bindings. Laravel is a very handy framework and allows the developer to perform tasks by simple means such as running raw SQL queries. However, avoiding this feature as much as possible ensures a better projection.

One important thing to notice here is you can’t bind column names with PDO. And, that’s why you should avoid using input from users to dictate the column name of a table. This also combines the columns used in an “ORDER BY” statement. Checking the column names against a whitelist will give you some flexibility.

SQL Injection
Some Common SQL Injection Examples Are:
  1. Retrieving hidden data, It enables you to modify an SQL query to return additional and extra results.
  2. Subverting application logic, It enables you to change a query to interfere with the system information.
  3. UNION attacks, It enables you to retrieve data from different databases and examine it to extract version and structure information of the database.
  4. Blind SQL injection, here the query results you control don’t get returned in the app’s responses.

Laravel Protection Against CSRF

CSRF aka Cross-Site Request Forgery is an age-old technique of hackers in which they entice a user to perform actions (such as clicks) that they don’t initially want to perform. Through this, the hacker partly circumvents the same-origin policy which disallows two websites to interfere with each other.

What is the Impact of This Attack?
The unwanted action that the user performs because of hackers, can lead to the change of their email address, change the password, or transfer money from their account to the hackers’. It depends on the action that how much access the hackers will get. In some cases, the hackers are able to get administrative control over their systems.

How does Laravel Help during CSRF?
Laravel keeps a track of each active user session and generates a CSRF token for each session automatically. This token helps understand the system whether the one making the authentication request is an original user or someone else.

XSS Protection

XSS attacks run on a simple hacking principle i.e. finding the weakness of a website and use that weakness (vulnerability) to inject malicious codes and scripts to gain access to the website. If they successfully inject their malicious codes, they can gain complete control over the victim’s website. It allows them not to only steal the data, but to even change the content of the entire website.

XSS Protection

Example: A hacker enter’s a simple message code to a blogging platform

<script>alert( ” You are hacked ” )</script>

Now, every time someone opens a blog on this website, this message will appear. This was just an example. Hackers can penetrate deep enough and can enter highly dangerous codes as well.

How Laravel Protects Against XSS
Laravel’s native support protects the code and website database in case of such attacks. The frameworks available today have made it easier to escape untrusted user input and mitigate XSS attacks. Some of the most used frameworks to avoid these vulnerabilities are React JS, AngularJS, and Ruby on Rails. These frameworks may have some limitations but they have great potential to automatically escape user input and help mitigate XSS attacks.

When it comes to preventing web security vulnerabilities, you should avoid picking up blacklist and go for whitelist because blacklist is considered less effective to secure web applications as attackers with a little good knowledge can bypass a blacklist filter quite easily.

Output encoding is the ultimate solution to prevent such web application attacks as It changes the untrusted user input to a safe form which means the input is displayed to the user as data without being used as code in the browser. This is how the special characters get translated to an equivalent form that the browser would not find significant.

Understanding that output encoding relies on the context of where data is being stored or output is important.
For example, the context could be anything from HTML, HTML entity, HTML attribute, JavaScript contexts to CSS contexts.

To avoid Cross-Site Scripting vulnerabilities, one ideal way is enabling an effective Content Security Policy (CSP).


What is HSTS?
HSTS or HTTP Strict Transport Security is a very advanced web security policy mechanism. It forces web browsers to interact with websites only through fortified and secure HTTPS connections (and never HTTP).

Used by websites to declare that they are secure and can be only accessed using a secure connection called HTTPS, It helps the websites to prevent their users from accepting insecure SSL Certificates. In simple words, HSTS is a widely supported term to safeguard HSTS enabled website users by ensuring that their browsers always connect to a website over HTTPS. So, with HSTS you don’t need the common and insecure practice of redirecting users from http:// to https:// URLs.

What does HSTS protect against?
Hackers are always lurking around to attack your app’s weak security points. HSTS protects you against MITM (Man in the middle) attacks, malicious code injection, and session hijacking.

Websites having HSTS are safe from the two additional vulnerabilities in SSL-enabled websites that are SSL protocol attacks and cookie hijacking. Other than making your website more secure, HSTS will make it load faster by eliminating an unnecessary step in the loading procedure.

Sensitive Data Exposure

Almost every month, we hear news about how some group of hackers breached the database of a big company or sometimes even a nation. And regardless of being high-profile companies, they used weak security measures. Two of the primary reasons for this are unsecured S3 buckets and weak password hashes. However, by employing the following practices, you can avoid this damage:

  • Your complete application should run over HTTPS only. And that, not without a TLS certificate. Write HSTS headers to provide a safe way to users who are trying to access the HTTP one.
  • Laravel is very good when it comes to securing passwords with an adaptive salted hashing function. It supports Bcrypt and Argon2. By all means, use them.
  • Save your time and efforts that will go into encrypting all the sensitive data that has been stored. Why not use the built-in encryption functions that Laravel has already provided.

Trusting user-uploaded files is another daunting mistake that most developers make. Even though all your users are genuine, they don’t know if their files are safe, validated, and contain no malware or virus. Doing this, you may put the entire system at great risk. The OWASP can come in handy here. Its Unrestricted File Upload page allows you to take several precautionary measures for such kinds of files. Here’s what you need to do using Laravel’s Validation Functionality:

  • Set up a minimum and maximum size for files that the user uploads.
  • If the user is uploading one after another file simultaneously, then limit that.
  • Rename the uploaded files according to your security demands.
  • Never upload files to a public directory.
  • Use third-party object storage facilities like AWS.

All this can be put together in a Laravel rule.

If a system parses XML, it will always find itself vulnerable to this. This kind of vulnerability was present in Facebook too years ago. To maintain a defense against such an attack is to disable external entity resolution while using a PHP XML parser. Make use of the ‘libxml_disable-entity-loader’ function.

If disabling this feature is out of your hands, then use the most updated version of the XML parser and SOAP. User-uploaded XML should always be monitored very closely.

Broken Access Control

If you remember the Citigroup incident exactly 10 years ago in 2011 when hackers exploited the poorly managed data of 200,000+ customers, you will understand the significance of broken access control. Authorization check is very important and you just can’t store the crucial data of your customers by changing the digits in the URL. That’s why it’s important to:

  • If your users are logged in and accessing their accounts, it’s important to put a wall of authentication checks to ensure whether the person accessing the account is actually the owner of that account or not.
  • Make use of Role-Based Access Control packages that Laravel allows developers to employ in order to manage user permissions.

Security Misconfiguration

Remember, an efficient system is the one that runs on the least functionality but the important ones. Disable all the extras that you don’t need. Why burden your systems and make them prone to risks? Therefore, always make a note of the following points:

  • Anything that is on your server or your website should be up to date.
  • Do not allow directory listing for your web server.
  • Debugging is bad for keeping certain kinds of data and information secret. Hence, disable it.

These are some of the best practices when it comes to securing your web or online PHP projects from malicious attacks. As we can see, Laravel makes for an amazing platform for providing extra layers of security in your projects and strengthening your web server’s defenses against breaches. The OSWP’s to-check list opens up a wide scenario to developers where they can understand how to tweak some changes to attain maximum security against common and intermediate web attacks.

Insufficient Logging and Monitoring

On average, Breaches mostly take 200 plus days before they’re detected. During this time span, your system is vulnerable to attacks and hackers can easily exfiltrate your important or sensitive data. However, by logging and monitoring all the performed tasks and activities these breaches can be detected.

How could Laravel help?

Coming with Monolog as a standard, Laravel enables you to integrate with a third-party service like Papertrail which means it logs each and every activity of the website or application such as login, request for password forgot or reset. No matter who is performing these activities, a member or an admin, all of them get logged in the records with a thorough and extensive audit trail.

Missing or Ineffective Integration with incident response enables hackers to get into the software system and take unauthorized control over the server data. However, logging everything could save you from this data breach. Using Laravel is the best way to keep yourself aware of any suspicious activity with receiving alerts for specific log events.

Nitin Chamola

Team Leader (Back-End)

    Related Articles