You compare two PHP folders safely by hashing every file first, then diffing path lists, then eyeballing only real conflicts in a three-way view; recovery works by restoring from the newest trustworthy source into a clean staging copy, never by copying directly over live code. Do the read-only comparison before any write, because a blind cp -r destroys exactly the evidence you need. This applies whether you're merging two versions of a project, return a drifted production tree to its repository state, or salvage a folder after a bad deploy.
The order matters more than the tool. Hash comparison tells you whether files differ; a textual diff tells you how; Git or a backup tells you which side is right. Skipping straight to a merge tool without either of the first two usually means you "recover" a stale folder over a current one. Nothing here requires a specific vendor product, though I'll name the common tools because that's how people actually search for this.
What "Two PHP Folders" Usually Means and What Changes the Answer
The phrase hides at least four situations, and each calls for a different recovery baseline.
Two copies of the same codebase. Folder A on your laptop, Folder B on a server, or A as last week's backup and B as today's mess. The repository or backup is the reference; one side is simply older.
A tracked folder and an untracked working copy. Very common: app/ in Git versus an edited app-copy/ on disk. Here Git's index gives you a free reference point, and the recovery target is "the version that should have been committed."
Two genuinely independent implementations. Two plugins, two forks, two branches of the same feature developed separately. There is no correct side, only a merger's judgment.
One folder against itself after an interrupted copy. Half-written files, truncated PHP classes, a .git directory that no longer matches its working tree.
The unit of comparison is a file path plus its content identity, not just a filename. Two files can share a name and be entirely unrelated; two files can differ by one missing semicolon and be nearly identical. Before touching anything, answer three questions in writing: which folder is the source of truth (repo, backup, or server), what changed since the last common state, and whether a recoverable snapshot of both folders exists. If you can't name a truth source, your job is to create one rather than to merge.
A subtlety specific to PHP: generated and environment artifacts live inside these folders and will spam your comparison. vendor/ (Composer dependencies), storage/ or var/cache/ in Laravel/Symfony projects, node_modules/ if you've mixed front-end assets in, compiled Blade or Twig templates, and .env files with credentials. Compare them only if dependency drift is the actual problem; otherwise exclude them and note the exclusions, because reconstructing them is a composer install job, not a merge job.
Prerequisites: Snapshots, Manifests, and a Clean Staging Area
You need three things before running a single command.
Read-only snapshots of both folders. On Linux or macOS, cp -a preserves permissions and timestamps; on Windows use robocopy /mir into a scratch location or a ZIP archive. If the folders are large, a full copy may be impractical, so at minimum archive them: tar -czf a-backup.tar.gz -C /path a for each side. The point is that no experiment you run afterward can destroy the original state.
A manifest per folder. One line per file, hash first, path second. A manifest is cheap, portable, and lets you re-run comparisons without re-reading every byte.
A staging directory outside both trees. All recovered output is assembled there, diffed, linted, and only then promoted. This single discipline prevents the most common failure: a half-finished copy overwriting a working tree mid-merge.
Free disk space should be roughly twice the larger folder plus room for snapshots. If either folder contains files over a few gigabytes (uncommon for PHP but possible with attachments or SQL dumps), note them and compare them separately by hash rather than by diff.
Step 1: Build Comparable Manifests
The goal is one canonical list per folder, with identical path formatting, so that a set comparison means something.
Run from the folder root so paths are relative. Absolute paths create noise when the two folders sit in different locations. On Linux or macOS:
cd /path/to/a && find . -type f -print0 | sort -z | xargs -0 shasum -a 256 > ../a-manifest.txt
On Windows PowerShell, Get-FileHash -Algorithm SHA256 combined with Get-ChildItem -Recurse -File and relative paths achieves the same thing; the exact pipeline is fiddly, so writing out a small script is usually faster than one-lining it.
Reject binary blobs from line diffs but not from hashing. Hashes work on anything. Text diffs on images produce garbage, so you want the manifest to be complete and the diff step to filter later.
Deal with line endings and BOMs now. PHP files that differ only because one side was saved with CRLF produce identical-looking diffs on every line. Decide explicitly whether trailing whitespace and line endings count as differences for your purposes. If they don't, normalize before hashing (or hash the normalized version) so you don't chase phantom conflicts.
Exclude deliberately and record it. A tight pattern list keeps the manifest meaningful: .git/, vendor/, node_modules/, cache directories, .DS_Store, Thumbs.db. Keep the exclusion list in a file next to the manifest so the comparison is reproducible and reviewable.
Success check: the manifest's line count roughly matches the number of PHP and asset files you expect, and spot-checking a hash by re-running one file's command reproduces the same digest. If not, your path formatting is inconsistent.
Step 2: Compare Manifests To Classify Every File
With two sorted manifests in the same format, three set operations classify everything:
Only in A — files that exist on one side and not the other. Only in B — same, opposite direction. In both, different hash — candidates for content conflict. In both, same hash — identical; ignore entirely.
Tools like comm (on sorted files) or diff --unchanged-line-format= give you the additions and deletions directly; sort-then-join on the hash-and-path columns catches the hash mismatches. Spelled out: comm -3 <(sort a-paths.txt) <(sort b-paths.txt) lists one-sided paths, and joining the manifests on path lets you compare the hash columns for shared paths. Doing this once as a script is worth the ten minutes; you'll run it again after every merge attempt.
This classification is the moment to be honest about what's happening. A large "only in A" set is usually not a merge problem—it's a checkout that's out of date, or a generated directory. A small, scattered set of differing files is a real content merge. A large differing set with identical paths smells like a wholesale version change or an editor reformatting everything.
Limits worth the awareness: hashes tell you not-equal but not how or which is newer. Timestamps are a weak proxy for recency because copies, restores, and checkouts reset them. Don't use mtime to decide which version wins except as a tiebreaker you've verified.
Step 3: Diff the Real Conflicts in a Three-Way View
Two-way diffs between the folders are enough to see disagreements but poor at resolving them, because they show you two versions with no anchor. A three-way merge—folder A, folder B, and their common ancestor (the last commit both descend from)—tells you which changes each side introduced and which edits overlap.
Establish the ancestor. If both folders are Git working trees, git merge-base gives you the commit; you can then diff each side against it. If one side is a backup, the backup is the ancestor. If you have no ancestor at all, say so explicitly and fall back to a straight two-way diff, accepting that every difference requires a human decision.
Diff in a reviewable interface. Command-line git diff --no-index a/ b/ or diff -ruN a b is fine for small sets; a visual tool such as VS Code's compare view, Meld, Beyond Compare, or KDiff3 makes PHP conflicts faster to read because function boundaries and whitespace stand out. The tool is a preference; the three-way structure is the method.
Order the review by risk. Configuration files (.env, config/*.php) first, because they're usually environment-specific and often should not be merged at all. Then application logic, then templates, then assets. Within logic, route definitions, schema migrations, and anything touching authentication or payment deserve individual attention—those are the files where a silent wrong choice costs the most.
Read for semantic conflicts, not just textual ones. Two files can merge cleanly and still be broken: one side renames a class, the other adds a method to the old class; one changes a function's parameters, the other adds a call site. PHP's dynamic nature makes these invisible to textual diffs. Keep a list of renamed/moved symbols as you go and search for them in the staged result afterward.
Success check: for every differing file, you can state in one sentence which side is correct and why (repository history, environment, or explicit design decision). If you can't, that file isn't ready to merge.
Step 4: Recover—Assemble Into Staging, Then Promote
Recovery here means "produce the correct folder," not "copy files back." Assemble it deliberately.
1: Seed staging from the truth source. If the repository is authoritative, check out the target branch fresh into staging. If a backup is authoritative, restore it. This gives you a known-good base rather than one side's accumulated drift. 2: Apply only the one-sided additions and deletions you've approved. Copy files that exist only in the salvaged side and belong in the result; delete files the truth source no longer has. 3: Apply the resolved conflicts file by file from your review notes—either take one side wholesale, hand-merge, or write a new version. 4: Regenerate the excluded artifacts. composer install for vendor/, the framework's cache-clear or build command for compiled templates, a fresh .env derived from .env.example with the correct values for the target environment. These should never be copied between environments with different credentials. 5: Compare staging's manifest against the intended result before promoting. This is the check most people skip. Your target manifest is the truth-source manifest adjusted by your documented decisions; if staging doesn't match it, you've applied something you didn't record. 6: Promote. Copy staging into place during a quiet window, or better, commit it on a branch and deploy through your normal pipeline so the change is reviewable and reversible.
Expect this to be slow for the first few files and to speed up as patterns repeat. Expect it to be right, which is the point.
Stop conditions. If staging fails to boot, lints, or pass its tests, do not keep patching in place—roll back to the last good state and re-examine your conflict decisions. If you cannot identify an ancestor or truth source and the folder holds production data, schema, or credentials, stop and get the owner involved; ad-hoc merging of sensitive configuration is where this goes truly wrong.
Step 5: Verify the Recovered Folder Before You Trust It
Verification is its own step, not a formality.
Syntax first, cheaply. php -l on every changed PHP file catches truncated files and broken merges in seconds. A loop over the changed-file list is a few lines of shell.
Then static analysis at the project's configured level (PHPStan, Psalm, or your framework's own checks). Static analysis is surprisingly good at catching the semantic conflicts from Step 3, like calls to methods that only existed on the discarded side.
Then the test suite, if one exists, and a manual smoke test of the specific features whose files changed. If there's no test suite, at minimum load the routes and pages that touch changed configuration.
Finally, compare manifests again between the verified result and your intended target. Any unexplained difference means an edit happened outside the process, and you should find it before promoting.
A worked illustration: suppose Folder A holds 1,240 tracked files after exclusions and Folder B holds 1,268. The manifests show 41 files only in B, 13 only in A, and 27 present in both with differing hashes, of which 19 differ only by line endings after normalization. That leaves 8 genuine content conflicts, 0 of them in migrations—a review you can finish in an afternoon rather than a weekend.
Choosing Between Tools Without Overthinking It
The comparison criteria that actually change your choice are: whether you have a three-way ancestor, whether the folders are under version control, and how large and noisy the file set is. Everything else is preference.
| Situation | Sensible approach | Why |
|---|---|---|
| Both folders are Git working trees with a common commit | git diff --no-index for spot checks; git merge or a branch-based merge for the real work | Git supplies the ancestor and records the resolution |
| One folder is a backup, the other live code | Restore backup into staging, diff by hash, apply approved changes | The backup defines the target state |
| No version control, no ancestor, modest size | Hash manifests plus a visual three-way tool with a manually chosen ancestor file | Honest about the missing anchor; keeps decisions explicit |
| Very large trees, mostly generated files | Manifest comparison with tight exclusions; content diffs only on the small conflict set | Avoids reviewing thousands of irrelevant differences |
A visual merge tool is worth its cost if you do this often; a terminal-only workflow is entirely sufficient if your conflict set is small and mostly configuration. Neither tool frees you from writing down which side won each file.
Edge Cases and Limits That Trip People Up
Symlinks and permissions. Hash comparison can follow or not follow links; choose deliberately, and preserve executable bits with cp -a rather than plain cp. Case-insensitive filesystems. Foo.php and foo.php can coexist on Linux and cannot on default macOS or Windows setups, so a folder that compares cleanly on one machine can fail to check out on another. Flag case-only differences explicitly. Filename encoding. Non-ASCII filenames can render differently across systems; normalize the manifest encoding before comparing. Very large or binary files. Compare by hash only; a diff is noise. A folder that is itself a Git repository. Comparing the working trees is fine, but remember .git/ holds the history you may need for recovery—never delete it as part of cleanup until the new state is verified and committed. Timestamps lie. Restores and copies reset them; treat them as hints, never as proof of recency.
The limit of the whole method is that it can't tell you intent. Hashes, manifests, and diffs show you that two files differ and how; only history, documentation, or a person who knows the project can say which version should survive. Budget time for that conversation rather than expecting a tool to make the call.
Run the comparison, classify, review the conflicts with a written decision each, assemble in staging, verify, promote. Do those things in that order and "compare and recover two PHP folders" stops being scary and becomes a repeatable file-level triage you can finish and defend.