Auditing a legacy PHP application for security vulnerabilities
By: Ernesto Buenrostro | November 20, 2026 | security, dev tools, and Tales from a Developer
Legacy PHP applications often evolve over many years without a framework or centralized security strategy. When a new team takes ownership of an application, it needs to understand the existing risks and establish a system for addressing them. Mugo Web recently helped a client manage these vulnerabilities in a third-party application we had taken responsibility for.
For this audit, we used static analysis and manual code review to identify any security issues in the application’s request handling, authentication, database queries, output encoding, sessions, cookies, redirects, and logging. We then worked with the client's development team to review remediation changes and re-audit the code.
Understanding the legacy PHP architecture
Our client was taking responsibility for a custom PHP application previously maintained by a single developer. The legacy application is a PHP codebase with more than 100 PHP files and no framework or CMS. Independent entry-point scripts handled request input, database access, business logic, and HTML generation. This flat architecture makes it possible for the same security weakness to appear in multiple locations.
How we audited the application
We focused on code paths that accept external input, process authentication or session data, interact with the database, generate HTML, perform redirects, or write to logs.
We used Psalm taint analysis to identify potential security issues and data flows. We then reviewed the findings manually, followed the relevant call chains, validated whether the issue was exploitable, and defined any necessary remediations.
Psalm taint analysis helped us trace how untrusted data moved through the application. We followed the data from its source, such as a request parameter or form field, to where it was used, including SQL queries, HTML output, redirects, and log messages.
The remediation was prioritized by severity of the issue.
| Phase | Approach |
| Static analysis | Psalm taint analysis |
| Manual review | Authentication, sessions, encoding, SQL, redirects |
| Validation | Follow data flows and confirm remediation |
| Risk prioritization | Exploitability and potential impact |
| Regression testing | Confirm existing application behavior |
Remediating the vulnerabilities
Once the audit was complete and prioritized, we organized the remediation around the data flaws identified during the audit. The main changes involved parameterized database queries, request validation, output encoding, authentication, sessions, redirects, and logging.
Example 1: SQL injection
The original query constructed SQL by concatenating variables directly into the query string.
$sql = "SELECT name FROM records WHERE id=$recordId AND NOT(name = '$excludedName')";
We changed the query to use parameterized values.
$sql = 'SELECT name FROM records WHERE id=? AND NOT(name = ?)';
$data = $db->executeQuery($sql, [(int) $recordId, $excludedName]);
The query and its values are passed separately, so the database driver can treat the values as data rather than SQL syntax. Casting $recordId to an integer adds input normalization, but parameter binding is what prevents $excludedName from being interpreted as SQL.
Example 2: Input validation
The original code accepted the request value directly and reused it in several operations: a database query, persistence, and URL construction.
if (isset($_POST['related_id'])) {
$query = 'SELECT * FROM records WHERE id=?';
$statement = $db->run_query($query, [$_POST['related_id']]);
$record = $statement->fetch(PDO::FETCH_ASSOC);
...
}
$db->save_user_data($db->current_user, 'related_id', $_POST['related_id']);
...
$result['path'] = 'details.php?id=' . $_POST['related_id'];
We converted the request value to an integer and rejected non-positive IDs before using it.
if (isset($_POST['related_id'])) {
$relatedId = (int) $_POST['related_id'];
if ($relatedId <= 0) {
$result['error'] = 'Invalid record ID.';
json_out($result);
exit;
}
// Continue using $relatedId...
}
The validated $relatedId was then used consistently in database queries, persistence, and URL construction, reducing the risk of unexpected values reaching downstream operations.
Example 3: Sensitive information in logs
The application logged database connection details, including the database username and password.
error_log("new PDO('mysql:dbname='. $dbname .'; host=' . $dbserver . '; charset=utf8', $dbuser, $dbpass)");
We removed the credentials from the logs and retained a generic error message for troubleshooting.
error_log('Database connection error.');
Logging errors is useful, but logs must be treated as sensitive data.
We also remediated findings related to output encoding, authentication and password handling, CSRF protection, session and cookie security, and user-controlled redirects.
For example:
- Output encoding
- Psalm identified request data flowing into the HTML rendering destination without appropriate encoding.
- We added centralized HTML escaping, input allowlisting and sanitization, safe JSON encoding for AJAX responses, and per-request Content Security Policy headers.
- Authentication and passwords
- Findings included weak MD5 password storage, insecure password resets, short password requirements, and privilege escalation through parameter overwrite.
- We removed local password logins and now use SSO only. Sessions are safer too: a new session ID is issued at login, session IDs are stored hashed, and users can’t grant themselves higher privileges.
- CSRF
- Several forms and links performed admin or destructive actions without checking a request token.
- We now issue a token per session, include it in every form and request, and verify it on the server.
- Sessions and cookies
- Session cookies weren’t marked HttpOnly, Secure, or SameSite. Session IDs were generated with mt_rand, which isn’t cryptographically secure.
- We now ignore cookie values until they’re verified, hardened session cookies, and generate session IDs with a cryptographically secure random source.
- Redirects
- Findings included open redirects and potential HTTP header injection through CRLF characters.
- We added safe relative-URL handling, sanitized login redirects, removed external GET redirects, and URL-encoded user-supplied values in redirect URLs.
How we validated the fixes
We re-ran Psalm after each remediation cycle and reviewed the remaining findings, confirming that the relevant taint flows were addressed and identifying cases requiring further work. We also manually reviewed the remediated code, and regression testing confirmed that the application continued to behave as expected.
| Metric | Result |
| Initial Psalm errors | 151 |
| Final Psalm errors | 0 |
| Regression testing | Completed |
The final Psalm scan reported no errors under the configured analysis settings. This indicates that the findings addressed by the remediation process were resolved within the scope of the analysis; it does not establish that the application is free of security vulnerabilities. Static analysis has limitations, including incomplete code coverage and reliance on inferred types when types are not explicitly declared.
What we learned
Static analysis is a starting point
Automated tools identify potential issues, while manual review establishes context and confirms the appropriate fix.
Legacy architecture can repeat security weaknesses
Independent implementations of request handling, database access, and output generation can lead to inconsistent security controls.
Fix patterns, not just individual findings
Shared approaches to database queries, input validation, and output encoding help address recurring vulnerability categories.
Make validation part of remediation
Repeated analysis and regression testing help verify security changes while preserving existing application behavior.
Owning a legacy application means understanding its security risks, fixing known vulnerabilities, and setting up a process for ongoing maintenance. Static analysis and manual code review help teams find weaknesses and prioritize fixes without unnecessary disruption. If your organization is taking over a legacy system, Mugo can help you assess the codebase, identify security risks, and plan remediation.

