backMarch 4, 2025

OWASP Top 10 for PHP Developers

The OWASP Top 10 is a list of the most critical security risks in web applications. This post follows the 2025 edition and shows what each risk looks like in PHP code, and how to fix it.

The examples use Symfony. A lot of these problems are already solved by the framework, as long as you use what it offers instead of writing your own version.

A01: Broken Access Control

Access control decides what a logged-in user is allowed to do. It breaks when your code checks that someone is logged in, but not whether they may touch this specific record.

#[Route('/profile/{id}/edit', methods: ['POST'])]
public function edit(User $user, Request $request): Response
{
    // Any logged-in user can edit any profile by changing the ID in the URL
    $this->profileUpdater->update($user, $request->getPayload()->all());

    return $this->json(['message' => 'Profile updated']);
}

Changing /profile/12/edit to /profile/13/edit is all it takes. This is called an IDOR (Insecure Direct Object Reference), and it's still one of the most common bugs out there.

Put the rule in a voter, so it lives in one place:

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Vote;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

final class ProfileVoter extends Voter
{
    protected function supports(string $attribute, mixed $subject): bool
    {
        return $attribute === 'PROFILE_EDIT' && $subject instanceof User;
    }

    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token, ?Vote $vote = null): bool
    {
        $currentUser = $token->getUser();

        return $currentUser instanceof User && $currentUser->getId() === $subject->getId();
    }
}

And check it on the controller:

#[Route('/profile/{id}/edit', methods: ['POST'])]
#[IsGranted('PROFILE_EDIT', subject: 'user')]
public function edit(User $user, #[MapRequestPayload] ProfileUpdate $update): Response
{
    $this->profileUpdater->update($user, $update);

    return $this->json(['message' => 'Profile updated']);
}

The ProfileUpdate DTO also fixes a second problem: the old version passed the whole request into the update, so a user could send "roles": ["ROLE_ADMIN"] along with their new name.

Server-side request forgery

SSRF is part of A01 since 2025. It happens when your server fetches a URL that the user controls:

public function fetchPreview(string $url): string
{
    return file_get_contents($url);
}

An attacker sends http://169.254.169.254/latest/meta-data/ and your server happily returns its own cloud credentials. Or http://localhost:6379 to talk to your Redis.

Checking the URL yourself is harder than it looks. A hostname can resolve to an internal IP, and a safe URL can redirect to an unsafe one. Symfony's NoPrivateNetworkHttpClient handles this for you. It checks the resolved IP address on every request, including redirects:

use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpClient\NoPrivateNetworkHttpClient;

$client = new NoPrivateNetworkHttpClient(HttpClient::create());

$response = $client->request('GET', $url, [
    'timeout' => 5,
    'max_redirects' => 2,
]);

If you know which hosts you need to call, like a fixed set of webhook providers, check against an allowlist on top of that.

A02: Security Misconfiguration

The code is fine, but the server isn't. Debug mode in production, default credentials, error messages with stack traces, directories that should never be public.

The most common one in PHP projects: a production server that still shows errors.

; php.ini in production
display_errors = On

Turning error reporting off completely isn't the fix either, because then you lose your logs. Hide errors from users, log everything:

; php.ini in production
display_errors = Off
log_errors = On
error_reporting = E_ALL

In Symfony, make sure production runs with:

APP_ENV=prod
APP_DEBUG=0

With debug on, Symfony shows full stack traces, and the profiler exposes requests, environment variables, and database queries to anyone who finds it. Install the profiler as a dev dependency only (composer require --dev symfony/profiler-pack), so it doesn't even exist on your production server.

A03: Software Supply Chain Failures

New in 2025, and broader than the old "Vulnerable and Outdated Components". It covers everything you didn't write yourself: Composer packages, npm packages, base images, CI actions.

Composer has the most important tool built in:

composer audit

It checks your installed packages against known security advisories. Run it in CI so a vulnerable dependency fails the build. The Gitea Actions post shows how to set up a pipeline where you can add this as a step.

You can also make Composer fail on abandoned packages:

{
    "config": {
        "audit": {
            "abandoned": "fail"
        }
    }
}

A few more habits that help:

  • Commit composer.lock and deploy with composer install, not composer update. Production gets exactly the versions you tested.
  • Look at a package before you add it. Who maintains it, when was the last release, how many people use it?
  • Pin CI actions and base images to a version instead of latest.

A04: Cryptographic Failures

Weak hashing, weak encryption, or no encryption where you need it.

Passwords

Never store passwords as plain text, and never use md5() or sha1() for them. Symfony's password hasher picks a strong algorithm for you:

# config/packages/security.yaml
security:
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
$user->setPassword($this->passwordHasher->hashPassword($user, $plainPassword));

auto currently means bcrypt or Argon2, depending on what your PHP installation supports. When a better algorithm becomes the default, Symfony rehashes passwords automatically on the next login.

Encrypting data

This is what you'll find in a lot of older code:

$key = 'hardcoded-secret-key';
$encrypted = openssl_encrypt($data, 'des-ede3-cbc', $key);

A hardcoded key, an outdated cipher, and no initialization vector. Switching to AES-256-CBC isn't enough either: CBC without a MAC doesn't detect tampering, and getting the combination right yourself is easy to get wrong.

Use libsodium, which ships with PHP. sodium_crypto_secretbox encrypts and authenticates in one go:

final readonly class Encryptor
{
    public function __construct(
        #[\SensitiveParameter] private string $key, // 32 bytes, from a secret or env var
    ) {}

    public function encrypt(string $plaintext): string
    {
        $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);

        return base64_encode($nonce . sodium_crypto_secretbox($plaintext, $nonce, $this->key));
    }

    public function decrypt(string $encoded): string
    {
        $decoded = base64_decode($encoded, true);
        $nonce = substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
        $ciphertext = substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);

        $plaintext = sodium_crypto_secretbox_open($ciphertext, $nonce, $this->key);

        if ($plaintext === false) {
            throw new \RuntimeException('Decryption failed: data was modified or the key is wrong.');
        }

        return $plaintext;
    }
}

Generate a key once with sodium_crypto_secretbox_keygen() and store it with Symfony secrets, not in your code.

A05: Injection

User input ends up in a query or command and gets executed as code.

SQL injection

$sql = "SELECT * FROM users WHERE username = '$username'";
$user = $this->connection->fetchAssociative($sql);

A username like ' OR '1'='1 returns the first user in the table. Use parameters, always:

$user = $this->connection->fetchAssociative(
    'SELECT * FROM users WHERE username = ?',
    [$username],
);

Doctrine's QueryBuilder and repositories do this for you, as long as you use setParameter() and don't glue strings together.

Command injection

exec("convert {$filename} -resize 100x100 thumbnail.jpg");

A filename like image.jpg; rm -rf ~ runs a second command. Symfony's Process component takes the command as an array, so every argument is passed as one value and the shell never interprets it:

use Symfony\Component\Process\Process;

$process = new Process(['convert', $path, '-resize', '100x100', $thumbnailPath]);
$process->mustRun();

Also don't use the user's filename for files on disk. Generate your own, for example with a UUID, and keep the original name in the database if you need it.

Cross-site scripting

Twig escapes output by default. XSS usually comes back in through |raw, or by building HTML in PHP. Use |raw only for content you've sanitized yourself, for example with the HTML Sanitizer component.

A06: Insecure Design

The code does exactly what it was designed to do, but the design itself is the problem. No amount of careful coding fixes that.

A classic example is a password reset that emails a new password:

public function resetPassword(string $email): void
{
    $user = $this->users->findOneByEmail($email);
    $newPassword = bin2hex(random_bytes(8));
    $user->setPassword($this->hasher->hashPassword($user, $newPassword));

    $this->mailer->send((new Email())
        ->to($email)
        ->text("Your new password is: $newPassword"));
}

Anyone who knows your email address can reset your password, which locks you out. The new password sits in plain text in a mailbox forever. And there's no limit on how often someone can trigger it.

A better design:

  • Send a link with a random token, not a password.
  • Store only a hash of the token, so a database leak doesn't give out valid reset links.
  • Make the token expire after a short time and work only once.
  • Rate-limit the reset form.
  • Show the same message whether the email exists or not, so the form can't be used to check which addresses have an account.

You don't have to build this yourself. SymfonyCasts ResetPasswordBundle implements all of it, and make:reset-password generates the controller and templates.

The lesson is broader than password resets: think about how a feature can be misused before you build it, not after.

A07: Authentication Failures

Problems with how users log in and how sessions are handled: weak passwords, brute force, session fixation.

The biggest risk here is building login yourself. A hand-written login that stores the user ID in the session forgets to regenerate the session ID, which allows session fixation. It also has no brute-force protection.

Symfony's security component handles both. Configure a login method and turn on throttling:

# config/packages/security.yaml
security:
    firewalls:
        main:
            json_login:
                check_path: api_login
            login_throttling:
                max_attempts: 5
                interval: '15 minutes'

On every successful login, Symfony migrates the session to a new ID by default. Login throttling needs the rate limiter component: composer require symfony/rate-limiter.

Password rules

Rules like "at least one uppercase letter, one digit, and one special character" don't help much. Users respond with Password1!. The NIST guidelines recommend focusing on length and blocking passwords that are known to be leaked.

Symfony has constraints for exactly that:

use Symfony\Component\Validator\Constraints as Assert;

final class ChangePassword
{
    #[Assert\Length(min: 12, max: 4096)]
    #[Assert\PasswordStrength(minScore: Assert\PasswordStrength::STRENGTH_MEDIUM)]
    #[Assert\NotCompromisedPassword]
    public string $newPassword = '';
}

NotCompromisedPassword checks the password against the Have I Been Pwned database. It only sends the first five characters of the password's SHA-1 hash, so the password itself never leaves your server.

A08: Software or Data Integrity Failures

Your application trusts code or data without checking that it hasn't been changed.

Scripts from a CDN

<script src="https://cdn.example.com/library.min.js"></script>

If that CDN gets compromised, the attacker's JavaScript runs on your site. Subresource Integrity makes the browser check a hash first:

<script
    src="https://cdn.example.com/library.min.js"
    integrity="sha384-..."
    crossorigin="anonymous"></script>

If the file doesn't match the hash, the browser refuses to run it. Most CDNs show the integrity hash next to the URL. Better yet, bundle the file with your own assets.

Updates and downloads

Downloading an update and running it without checking where it came from is the same problem on the server side. Verify a signature before you use the file:

$verified = openssl_verify($updateZip, $signature, $publicKey, OPENSSL_ALGO_SHA256);

if ($verified !== 1) {
    throw new \RuntimeException('Update signature verification failed.');
}

Unserialize

Never call unserialize() on data a user can change, like a cookie or a hidden form field. A crafted string can create objects of any class in your application and trigger their magic methods. Use json_decode() for data that crosses a trust boundary.

A09: Security Logging & Alerting Failures

If nobody notices an attack, it can keep going for months. This category was renamed in 2025 from "monitoring" to "alerting": logs only help if someone actually gets notified.

Symfony dispatches events for every login, failed login, and logout. Listen to them and log to a dedicated channel:

# config/packages/monolog.yaml
monolog:
    channels: ['security_audit']
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Security\Http\Event\LoginFailureEvent;
use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;

final readonly class SecurityAuditListener
{
    public function __construct(
        private LoggerInterface $securityAuditLogger,
    ) {}

    #[AsEventListener]
    public function onLoginSuccess(LoginSuccessEvent $event): void
    {
        $this->securityAuditLogger->info('Login succeeded', [
            'user' => $event->getUser()->getUserIdentifier(),
            'ip' => $event->getRequest()->getClientIp(),
        ]);
    }

    #[AsEventListener]
    public function onLoginFailure(LoginFailureEvent $event): void
    {
        $this->securityAuditLogger->warning('Login failed', [
            'user' => $event->getPassport()?->getBadge(UserBadge::class)?->getUserIdentifier(),
            'ip' => $event->getRequest()->getClientIp(),
            'reason' => $event->getException()->getMessageKey(),
        ]);
    }
}

The $securityAuditLogger argument name is enough for MonologBundle to inject the logger for the security_audit channel.

What to log:

  • Logins, failed logins, and password changes
  • Permission changes and denied access
  • Deleting accounts or other important data, including who did it

What never to log: passwords, tokens, session IDs, and full credit card numbers.

Then make sure someone gets an alert. Send the security_audit channel to a tool that notifies you when, for example, failed logins from one IP suddenly spike. A log file that nobody reads doesn't detect anything.

A10: Mishandling of Exceptional Conditions

New in 2025. This is about what your application does when something goes wrong: an API that times out, a missing file, an unexpected null. The dangerous version is called failing open, where an error results in more access instead of less.

public function canDownload(User $user): bool
{
    try {
        return $this->licenseApi->hasValidLicense($user);
    } catch (\Throwable) {
        // Don't block users when the license server is down
        return true;
    }
}

The license server is down for an hour, so everyone gets free downloads. An attacker who can make that call fail (for example by sending a request that's slow to process) gets the same result.

Fail closed, catch only the exceptions you expect, and log what happened:

use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;

public function canDownload(User $user): bool
{
    try {
        return $this->licenseApi->hasValidLicense($user);
    } catch (TransportExceptionInterface $e) {
        $this->logger->error('License check failed', ['exception' => $e]);

        return false;
    }
}

The same goes for error messages. Showing $e->getMessage() to users leaks file paths, SQL queries, and library versions. In production, Symfony shows a generic error page and logs the details. Leave that in place instead of catching exceptions and echoing them yourself.