← Home ← Codex ← DEBT ← Engine
Browse by Category
+ added · ✎ updated 7d
← Back to glossary

basename()

PHP PHP 5.0+ Beginner
debt(d7/e3/b3/t7)
d7 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'only careful code review or runtime testing' (d7), since semgrep/psalm can flag user-supplied paths in file ops but the misuse (treating basename() as sufficient sanitisation) is semantic and typically caught only in security review.

e3 Effort Remediation debt — work required to fix once spotted

Closest to 'simple parameterised fix' (e3), per quick_fix: combine basename() with realpath() and whitelist validation — a small pattern replacement at each call site rather than one-line swap.

b3 Burden Structural debt — long-term weight of choosing wrong

Closest to 'localised tax' (b3), as basename() usage is typically confined to upload/file-handling components rather than spreading across the system, though applies_to covers web and cli contexts.

t7 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'serious trap' (t7), per misconception: developers reasonably assume a function named basename() in a security context sanitises the filename, but it only strips directory components and leaves null bytes, locale issues, and other injection vectors — contradicts the safety implied by the name.

About DEBT scoring →

Also Known As

PHP basename() filename extraction path basename

TL;DR

Returns only the filename component of a path, stripping any directory prefix — a simple path traversal defence.

Explanation

basename($path) extracts just the filename from a path string, discarding any directory component. This means ../../etc/passwd becomes passwd, preventing directory traversal in simple filename lookups. However, basename() alone is not sufficient protection — it doesn't prevent a user from naming a file to overwrite an existing one, and does not validate the extension or content. Use it as one layer alongside extension allowlists and realpath() checks.

Common Misconception

✗ basename() is safe to use directly on user-supplied paths. basename() strips directory components but does not prevent null byte injection in older PHP versions and does not validate that the result is a safe filename — always combine with additional sanitisation for upload handling.

Why It Matters

basename() strips directory components from a path, but it does not validate or sanitise — null bytes, Unicode directory separators, and path components on other OS types can still be problematic.

Common Mistakes

  • Using basename() as a security measure against path traversal — it strips the directory but does not prevent other injection vectors.
  • Trusting basename() output as a safe filename for includes — the result still needs whitelist validation.
  • Not realising that basename() is locale-dependent for multibyte characters — use the $suffix parameter carefully.
  • Combining basename() output with a base directory via string concatenation without realpath() validation after joining.

Code Examples

✗ Vulnerable
// basename() alone is not sufficient for safe file access:
$file = basename($_GET['file']);
include '/var/www/templates/' . $file; // Still dangerous without whitelist
// Attacker bypasses with null byte on old PHP: shell.php%00.html
✓ Fixed
// basename() extracts filename, stripping any path components
basename('/var/www/uploads/image.jpg');  // 'image.jpg'
basename('../../../etc/passwd');          // 'passwd'
basename('photo.jpg', '.jpg');            // 'photo' — strip extension

// Use in file downloads to strip path traversal from user input:
$safeFile = basename($_GET['file'] ?? '');
$path     = '/var/www/uploads/' . $safeFile;
if (!file_exists($path)) abort(404);
readfile($path);

// Always combine with realpath() for full safety:
$base = realpath('/var/www/uploads');
$path = realpath($base . '/' . $safeFile);
if (!$path || !str_starts_with($path, $base . DIRECTORY_SEPARATOR)) abort(403);

Added 15 Mar 2026
Edited 22 Mar 2026
Views 133
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings S 1 ping M 0 pings T 1 ping W 0 pings T 0 pings F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W 1 ping T 0 pings F 0 pings S 1 ping S 2 pings M 1 ping T 0 pings W 0 pings T 1 ping F 0 pings S 1 ping S 1 ping M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 1 ping M
Amazonbot 1
No pings yesterday
Amazonbot 17 PetalBot 11 Ahrefs 9 Perplexity 8 SEMrush 8 Bing 8 Google 6 Unknown AI 5 ChatGPT 4 Scrapy 4 Claude 3 Sogou 2 Applebot 2 Meta AI 1 Brave Search 1 Common Crawl 1
crawler 85 crawler_json 3 your_contextpost 1 pre-tracking 1
🧱 FUNDAMENTALS — new to this? Start with the ground floor.
PHP php A server-side scripting language that generates web pages and APIs — the code runs on the server, and only its output (usually HTML or JSON) reaches the browser.

PHP is often the first server-side language people meet, and understanding its execution model — script starts fresh on every request, no memory between requests — explains most of how the web backend works: sessions, databases, and caching all exist to bridge that per-request amnesia.

💡 Start with PHP 8.x, declare(strict_types=1), and PDO — skip any tutorial that mentions mysql_query().

Ask Codex about PHP →
⚡ DEV INTEL Tools & Severity
🟡 Medium ⚙ Fix effort: Low
⚡ Quick Fix
Use basename() to extract just the filename from a path — but note it only strips directory components, not null bytes or dangerous characters; combine with realpath() and path validation for secure use
📦 Applies To
PHP 5.0+ web cli
🔗 Prerequisites
🔍 Detection Hints
User-supplied filename used in file operations without basename() to strip directory components; path traversal possible via ../ in filename
Auto-detectable: ✓ Yes semgrep psalm
⚠ Related Problems
🤖 AI Agent
Confidence: Medium False Positives: Medium ✗ Manual fix Fix: Low Context: Line
CWE-22


✓ schema.org compliant