New Relic Now ¿Sueñas con innovar más? Comienza a vivir tu sueño en octubre.
Reservar plaza
Por el momento, esta página sólo está disponible en inglés.

PHP is one of the most widely-used programming languages for server-side applications. Projects like WordPress, Drupal, and Laravel use PHP under the hood, and PHP-based applications account for over 77% of all web applications.

If you’re using PHP in your codebase, it’s important to be aware of the most common security vulnerabilities and take steps to mitigate them. Security breaches have tremendous costs that go beyond the bottom line, leading to lost users, lost reputation, and potential harm to your codebase as well as to your users and employees. In this article, you’ll learn about:

  • Common PHP security threats
  • How to monitor your PHP application for security issues
  • How to improve your overall PHP security, both in general and with New Relic
NEW RELIC PHP INTEGRATION
php logo
Start monitoring your PHP data today.
Install the PHP quickstart Install the PHP quickstart

Common PHP security threats

Let’s take a look at some of the most common PHP vulnerabilities you need to watch for. This isn't a complete list, and hackers regularly find new security vulnerabilities to exploit.

  • Cross-site scripting (XSS): XSS involves an attacker injecting malicious code into a page. When a user goes to that page, the code is then executed in the user’s browser. This can allow attackers to gain access to a user’s information and potentially even perform actions from a user’s account or machine. You can reduce the risk of XSS attacks with input validation of forms as well as output encoding, which involves translating special characters (specifically ones commonly used in XSS attacks) to other characters. Some PHP frameworks like Laravel include built-in protections against XSS. Another approach is to use an HTML escaper, which sanitizes input from users, preventing malicious code from being executed.
  • SQL injection: With SQL injection, hackers insert malicious code into a SQL query in order to gain access to your database. To prevent SQL injection attacks, you need to sanitize user input before it's passed to the database. You can pass user input into PHP methods like sanitize() and filter_var() for sanitization. You should also use parameterized queries instead of passing user input directly into a SQL query.
  • Cross-site request forgery (CSRF): With a cross-site request forgery attack, the attack attempts to trick users into submitting requests that alter data on your server. For example, an attacker could create a webpage that contains a form that looks identical to the login form for your site. If a user submits the form with their credentials, the attacker can gain access to the user's account. To protect against CSRF attacks, you can add a unique token to each form submission. This token is typically generated using PHP's session management capabilities. The server can then verify that the token is valid before processing the request. You should also use HTTPS protocol for all forms and verify the HTTP Referrer header on each request.
  • Session hijacking: Session hijacking, which is also known as session fixation, exploits a vulnerability in the way PHP handles session IDs. By default, PHP simply increments a counter for each new session. However, attackers can exploit this by predicting the next ID. This allows the attacker to take over a user's session and perform malicious actions. You should use a more secure method for generating session IDs such as using random numbers. You can also use the Secure Sockets Layer (SSL) to encrypt communications between the server and the client.
  • Buffer overflows: Buffer overflows happen when data is written to a buffer that is either too small or doesn't exist. This can lead to data corruption or crash your application, resulting in outages. Attackers can exploit buffer overflows to inject malicious code into applications or cause denial-of-service attacks. You can mitigate the risk by ensuring that your buffers are properly sized and bounds-checked before writing data to them. You should also use safe functions that avoid buffer overflows, such as PHP’s strncpy() function.
  • Denial of Service (DoS) and Distributed Denial of Service (DDoS): Both DoS and DDoS attacks are designed to flood your system with requests, using up your application resources and causing an outage. Distributed denial of service attacks are more sophisticated because the attacker uses a network of infected computers, also known as a botnet, to carry out the attack. DDoS attacks can be very difficult to defend against because they can generate huge amounts of traffic. Attacks can occur at either the infrastructure layers or application layers. To protect against DDoS, you first need to minimize the possible attack points, such as unnecessary ports or protocols. Using content delivery networks and load balancers can also help reduce the vulnerable surface area of your application. To handle DoS and DDoS attacks when they occur, you should use a monitoring tool like New Relic to alert your teams on metrics such as a sudden and suspicious increase in traffic or a reduction in your application’s capacity to handle requests. You’ll likely also see a significant slowdown or halt in the time it takes to process user requests. Having the flexibility to increase server capacity as well as network capacity (with a CDN, for example) can help mitigate these kinds of attacks. You can also implement rate limiting to prevent an excessive amount of traffic from overwhelming your hosts.
  • Password cracking: Hackers can crack passwords via brute force attacks and dictionary attacks. You can help prevent user passwords from being cracked by requiring longer passwords with additional special characters and also including recommendations or requirements to update passwords regularly. For your employees, your requirements should be stricter and you should also include multi-factor authentication so that attackers can’t break into an account with just a password.
  • Man-in-the-middle (MitM): In a MitM attack, an attacker intercepts communication between two parties, either to eavesdrop on the communication, manipulate exchanged data, or both. PHP session cookies are a vulnerability that can lead to hijacked user sessions and MitM attacks. PHP's remote file inclusion (RFI) vulnerability can also be exploited to inject malicious code into a PHP application. You can protect against MitM attacks by validating all user input and taking steps to properly secure all cookies. It’s also important for all communications to be sent via HTTPS.
NEW RELIC VULNERABILTY MANAGEMENT
New Relic Vulnerability Management data sheet
Troubleshoot faster with New Relic Vulnerability Management
Overcome security blindspots today Overcome security blindspots today

How to improve your overall PHP security

We've covered some of the basic security approaches for each kind of attack, but let's take a deeper look at improving your PHP application’s security. There's only so much we can cover, so note that there are many things you can and should do to secure your PHP application beyond this list. For a more comprehensive list of secure coding practices, which apply to all programming languages including PHP, check out OWASP’s Secure Coding Practices-Quick Reference Guide.

  • Incorporate New Relic vulnerability management, which gives you a unified security view across your stack, including information about security vulnerabilities in your third-party dependencies.
  • Follow secure by design coding best practices. Your engineering teams should focus on building secure applications from the ground up. This includes principles such as fewest privileges, which means giving users only enough access privileges to perform necessary actions in your application. That way, even if a user’s account is compromised, attackers will have limited access to your application.
  • Assume that attacks will happen and be prepared for them. This is another principle of secure by design best practices. Assume that attacks can and will happen. By doing so, you won’t be caught off guard. This also includes adequate preparation, including team training, setting up protocols and operational guidelines for security breaches and outages, and having gamedays that simulate attacks to better prepare your teams for actual attacks when they happen.
  • Use secure hosting. Not every host provides security—consider using a hosting service that provides CDNs (for protection against DoS and DDoS attacks), firewalls (to prevent unauthorized attacks), and SSL certificates (to verify your website and prevent attackers from creating malicious copies of your site.)
  • Make your systems fault tolerant. Fault-tolerant design means that your systems can handle unexpected spikes in activity and usage. These spikes can occur for a number of reasons, including DoS and DDoS attacks. This might include using a content delivery network to ensure that users can still access content even during an attack, or it might entail having extra server space or flexibility in the cloud to scale up services during an attack. Conversely, you can also implement rate limiting as needed to minimize the impact of attacks.
  • Conduct security audits. You should periodically evaluate your system’s security and vulnerabilities. This includes security diagnostics, evaluating your system’s environment and configuration, and testing your code. New Relic vulnerability management allows you to evaluate all of your application’s vulnerabilities in one place, at any time.
  • Monitor activity in your application. You can use an application performance tool like New Relic to monitor key metrics that can be heavily impacted by attacks, including throughput and transaction rate.
  • Set up alerts for critical performance thresholds. Set up alerts on your monitoring and security tools so that your teams are notified of suspicious activity as quickly as possible.
  • Protect your database and use parameterization. There are many steps you should take to secure your database. One of the most important—and basic—is sanitizing user input through the use of parameterization.

    Here’s an example of an unsafe SQL query that doesn’t use parameterization:

    SELECT * FROM users WHERE name = '{$name}'

    A hacker can enter a malicious SQL statement so that your database reads the $name input as a command and execute the code. That could include commands that gather private information or even update or destroy rows in your database.

    Here’s an example of a parameterized query in MySQL:

    "SELECT name FROM users WHERE name = @name";

    MySQL uses @ to define a parameter. SQL statements can’t be parameterized, so a malicious user can’t pass a malicious statement through a parameter, making it safe from SQL injection.

    If you use Laravel, you can also use Eloquent ORM to easily create parameterized queries as well. Here’s an example:

    $user = DB::table('users')->where('name', $name)->get();

    Here, $name is passed in as a parameter using a where() clause.

Preventing security vulnerabilities with New Relic

Finding and patching security vulnerabilities before they cause serious breaches can be tough, especially when your stack potentially includes thousands of services and external dependencies. Ideally, you want a tool that gives you insight into security vulnerabilities across your stack.

As the next image shows, New Relic vulnerability management gives you a unified view of vulnerabilities across your stack.

You can see all open vulnerabilities as well as trends on untriaged vulnerabilities across your stack. You can also integrate security tools like GitHub Dependabot, Lacework, Snyk, and more, making it easier to get full visibility all in one place. Learn more about New Relic vulnerability management.

Application performance monitoring (APM) is also an important part of a proactive security stance. You can get started with the PHP quickstart in just a few minutes. The quickstart includes a dashboard with key performance metrics including transaction rate, error rate, and throughput. You’ll automatically get alerts when web transactions are taking too long or your application’s throughput is too low. Both of these indicators can be signs of errors in development—or that your system is being targeted by attacks. You can also set up your own alerts on a wide range of indicators so that your teams are notified of attacks before they overwhelm your application. The next image shows a New Relic dashboard with metrics from a PHP application, including error rate and throughput.

Once you are monitoring your PHP applications for security vulnerabilities and performance issues, you're ready for the next step—setting up alerts so that your teams are notified when issues arise.

If you're not sure yet whether New Relic is right for you, try out our free tier, which is free forever as long as you don't ingest more than 100 GB/month of telemetry data. In just a few minutes, you can get important security insights on your PHP applications—along with additional peace of mind. Feel free to learn more about how observability can help with security vulnerabililty.