Skip to content
Mohammed Kharbotli

~/blog/how-i-approach-an-unfamiliar-plain-php-codebase

How I Approach an Unfamiliar Plain PHP Codebase

Exploring an unfamiliar plain PHP application can be tricky. I share how I trace execution paths, uncover hidden dependencies, understand existing behaviour, and figure out what might break before making changes.

When I open an unfamiliar PHP application, one of the first things I try to understand is how it actually runs.

Not how it was supposed to be structured, or how someone intended it to work. I want to know what happens when a request comes in, which files get loaded, what those files do, and what else depends on them.

Plain PHP applications can be surprisingly difficult to navigate. Some are well organized, with clear responsibilities and sensible boundaries. Others have grown through years of small changes, where a shared include has gradually become responsible for half the application.

You don't always see that from the directory structure.

I've learned not to start by looking for things to refactor. First, I want to understand what I'm dealing with.

The question I keep coming back to is:

If I change this behaviour, what else might be affected?

That question influences almost everything I investigate.

Talk to the people who know the application

Before spending too much time reading code, I try to speak with whoever has been maintaining the application.

I usually start with a few straightforward questions:

  • Which parts of the application are difficult to change?
  • Are there scripts that someone still has to run manually?
  • What tends to go wrong after deployment?
  • Are there behaviours that look strange but must remain as they are?

The last question is particularly useful. Older applications often contain decisions that don't make much sense until someone explains the history behind them.

For example, if someone mentions that an import occasionally needs to be run again, I want to know why. Does it resume from where it stopped? Can it process the same records twice? Is there a manual cleanup step before rerunning it?

I also check whether the repository matches what's running in production.

Important parts of an application can live outside the source tree: a manually edited configuration file, a script on a particular server, or a deployment step that was never properly documented.

These details can change how I approach the code, so I'd rather discover them early.

Find the actual entry points

My next step is to work out where execution begins.

In a framework application, there's usually a fairly obvious request lifecycle. In plain PHP, I don't assume there is one.

Does every request go through index.php? Can someone access admin.php directly? Are there webhook endpoints? Do scheduled scripts use the same initialization code as web requests?

I start with a simple inventory:

rg --files -g '*.php' -g '!vendor/**'

Then I search for places where the application interacts with its environment:

rg -n \
  '\$_(GET|POST|REQUEST|FILES|SESSION)|\$argv|session_start|php://input' \
  -g '*.php' -g '!vendor/**'

They don't tell me everything, but they give me somewhere to start. Dynamic includes, rewrite rules, and server configuration can make the actual execution paths less obvious.

Cron jobs and command-line scripts deserve particular attention.

A scheduled import might write to exactly the same tables as the web application, but it won't necessarily go through the same authentication, validation, or authorization logic.

That matters when deciding whether a change is safe. A function that appears to be used by one web page might also be used by a nightly job.

Before changing shared code, I want to know who calls it.

Spend time understanding the includes

This is usually where I slow down a little.

Consider a typical PHP file:

require 'config.php';
require 'functions.php';
require 'auth.php';

It looks straightforward, but those filenames don't tell me what the files actually do.

config.php might establish a database connection and start a session. functions.php might execute queries as soon as it's included. auth.php might redirect the user, call exit, or populate variables that other files expect to exist.

In plain PHP, includes can create particularly confusing dependencies because the included code inherits the variable scope of the location where it's included.

For example:

$accountId = (int) $_SESSION['account_id'];
 
require __DIR__ . '/load_orders.php';
 
renderOrders($orders);

There might be no obvious declaration of $orders in the current file. It simply appears after the include because load_orders.php created it.

When I encounter code like this, I read the included file and follow the variables in both directions. What does it expect to exist before execution? What does it create? Does it modify anything else?

I resist the temptation to immediately turn every include into a function.

That can be a good improvement eventually, but moving included code into a function changes its scope. If other files rely on variables being created at the inclusion point, the refactoring can break behaviour that wasn't immediately obvious.

Once I understand the dependency, I can start making it explicit:

function loadOrders(PDO $db, int $accountId): array
{
    $stmt = $db->prepare(
        'SELECT id, status, total_minor
         FROM orders
         WHERE account_id = :account_id
         ORDER BY id DESC
         LIMIT 50'
    );
 
    $stmt->execute(['account_id' => $accountId]);
 
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

Now the function tells me what it needs and what it returns.

I don't need a framework to get that kind of clarity. I just need to be careful about replacing implicit behaviour with explicit dependencies.

Check which PHP runtime you're actually dealing with

One thing I never assume is that the PHP version and configuration used by the command line are identical to those used by the application.

I start with:

php -v
php --ini
php -m

These tell me about the CLI environment. If the application runs through PHP-FPM or Apache, I check that runtime separately.

The difference can matter more than expected. An extension might be available in CLI but missing from PHP-FPM. A timezone setting might differ. Filesystem permissions can also behave differently depending on which user executes the process.

Working directories deserve attention too.

This is the sort of code that looks harmless:

require 'config.php';
 
file_put_contents('exports/report.csv', $csv);

But where does exports/report.csv actually end up? That depends on the execution context.

For includes, I generally prefer paths based on __DIR__:

require __DIR__ . '/config.php';
 
$exportPath = $configuredExportDirectory . '/report.csv';

I also want to know where application data is stored. Writing generated files into a release directory can become a problem when deployments create new release directories and switch between them.

If Composer is present, I look through composer.json, composer.lock, and any configured scripts or plugins before running installation commands. Composer scripts and plugins can execute code during installation and updates, so they're part of the application's setup process rather than just configuration.

If Composer isn't present, I look for copied libraries and local modifications. An application can have quite a few dependencies without having a dependency manifest.

Follow something that actually matters to the business

At this point, I usually stop browsing files randomly.

Instead, I pick one operation and follow it all the way through.

It might be a checkout, a cancellation, an import, or a subscription renewal. The particular operation matters less than choosing something that changes application state.

Suppose I find this:

saveOrder($db, $order);
chargeCustomer($gateway, $order);
sendConfirmation($mailer, $order);

The happy path is only part of the story. I also need to understand what happens when something fails.

What if the order is saved but the payment request times out? What if the payment succeeds but the application never receives the response? Can the customer submit the same form twice and create duplicate orders?

And what happens if sending the confirmation email fails? Does the application report that checkout failed, even though the customer has already been charged?

Answering these questions usually tells me more than reading a dozen unrelated functions.

I also look at the database transaction boundaries. Is the order saved inside a transaction? When is it committed? What happens if an exception occurs halfway through the operation? Are external API calls happening while a database transaction is open?

Prepared statements address parameter handling, not authorization. I still need to check authorization at the point where the operation happens. A query can use prepared parameters correctly and still allow someone to modify another customer's order if the application doesn't verify ownership.

I also check how data is rendered back into HTML. Protecting a database query doesn't protect a page from displaying untrusted HTML or JavaScript.

Error handling is another thing I inspect early.

Consider:

try {
    importOrders($db, $file);
} catch (Throwable $e) {
    error_log($e->getMessage());
}
 
echo 'Import completed';

The message says the import completed, but the code doesn't establish that.

I wouldn't immediately rewrite this, though. First I'd check whether the import can partially commit, whether another process reads its exit code, and whether anyone depends on that output message.

It's tempting to fix the obvious problem without checking who else relies on the existing behaviour. That's exactly how a small maintenance change can turn into a bigger problem.

Look for problems that aren't obvious from reading the code

Once I understand an important execution path, I start looking at things that might affect its performance.

Repeated queries inside loops are an obvious place to look, but I don't stop there. Large result sets, remote calls without sensible timeouts, and unnecessary filesystem operations can all become problems as an application grows.

One PHP-specific issue I pay attention to is session locking.

With PHP's default file-based session handler, session_start() normally acquires an exclusive lock on the session file. Another request using the same session may have to wait until the lock is released or the first request finishes.

This can produce a confusing situation: one slow request makes other requests from the same user appear to hang.

For example:

session_start();
 
$userId = $_SESSION['user_id'];
 
$report = generateLargeReport($userId);

If the application doesn't need to modify the session during report generation, it may be possible to release the lock first:

session_start();
 
$userId = $_SESSION['user_id'];
session_write_close();
 
$report = generateLargeReport($userId);

It's a small change, but I wouldn't apply it blindly. If the rest of the script modifies $_SESSION, those changes won't automatically be saved. Releasing the lock also means another request can modify the session while the report is being generated.

Still, when someone tells me that the application becomes unresponsive while a report is running, session locking is one of the things I want to rule out.

Make sure I can tell whether a change worked

I don't want my first change to be based entirely on the assumption that the application still behaves as expected.

If tests already exist, I run them and establish a baseline. If there are no tests, I look for a small boundary where I can observe the behaviour I'm about to change.

Sometimes that's a calculation that can be tested independently. Other times it's a database operation that needs an integration test.

Scripts that call exit can be awkward to test by including them directly in a test runner. In those cases, running the script as a separate process is often more practical.

For an HTTP operation, I might start with something like:

$response = $client->post('/cancel_order.php', [
    'form_params' => [
        'order_id' => $orderId,
        'csrf_token' => $csrfToken,
    ],
]);
 
self::assertSame(303, $response->getStatusCode());
 
self::assertSame(
    'cancelled',
    $fixtures->fetchOrderStatus($orderId),
);

This assumes an authenticated client, redirects disabled, and an isolated test database.

I also want to test what should happen when the operation is rejected. For example, can one customer cancel another customer's order? What happens if the order has already been cancelled?

It's easy to write a test proving that the happy path works. The more interesting question is whether the application correctly handles the situations where it shouldn't proceed.

I prefer small, controlled fixtures because I want to know exactly what a test is exercising. Importing a large production database can give a false sense of coverage without making individual behaviours any easier to understand.

Decide what to change first

By now, I should have a reasonable picture of at least one important part of the application.

I usually keep a few notes as I go:

  • Things I've confirmed by reading or running the code.
  • Things I suspect but haven't verified.
  • Dependencies or behaviours I still don't understand.

That distinction matters. It's easy to spend an afternoon investigating something and gradually start treating an assumption as a fact.

For the first change, I prefer something relatively contained with an observable result. Maybe a hidden input can be removed, a repeated query can be avoided, or a failed import can finally report failure correctly.

It doesn't have to be a major refactoring. I'd rather make one small change that I can explain and verify than reorganize several files simply because their current structure bothers me.

There will usually be more things to improve once I understand the application better.

I don't need to understand every file before contributing. I need enough confidence in the part I'm changing to understand the consequences, test the result, and know what to look at if something goes wrong.