October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

How to Get a Filename, Extension, and Query String from a URL in PHP

Separate a URL’s path and query with parse_url(), extract the final path segment with basename(), and use pathinfo() when you need the extension.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use parse_url() to separate a complete URL into its path and query, then pass only the path to basename() to get its final segment. Append the query separately if you need the filename and the full query string together. For the current incoming request, start with $_SERVER['REQUEST_URI'].

Get the final filename and preserve its query string

This returns the final path segment followed by the original query string, keeping percent-encoded values such as %20 and %27 intact:

As an Amazon Associate I earn from qualifying purchases.

<?php
$url = 'https://www.domain.com.au/dev/website/shop-product.php?shopCategoryID=1&shopSubCategoryID=2&productID=1&title=Buy%20Blank%20T-Shirts%20Online&category=Men%27s%20T-Shirts';

$parts = parse_url($url);
$path = $parts['path'] ?? '';
$filename = basename($path);
$query = $parts['query'] ?? null;

$result = $filename . ($query !== null ? '?' . $query : '');
echo $result;
?>

The result is shop-product.php?shopCategoryID=1&shopSubCategoryID=2&productID=1&title=Buy%20Blank%20T-Shirts%20Online&category=Men%27s%20T-Shirts. The null check means no question mark is added when the URL has no query.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

parse_url() separates URL components; it does not validate that a URL is well formed or safe. Its query value remains encoded rather than being decoded.

Handle missing or unusable paths

A URL may have no path, end in a slash, or contain a query without a filename. If input may be malformed, check that parsing succeeded and that the parsed path is non-empty before using the result. An empty final segment is not a filename to rely on.

Get the filename or extension without the query

If you want only the last path segment, use basename() on the parsed path:

$filename = basename(parse_url($url, PHP_URL_PATH) ?? '');

For an extension, pass that filename to pathinfo():

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
$extension = pathinfo($filename, PATHINFO_EXTENSION);

basename() returns the trailing component of a path. pathinfo() can also provide filename and basename details. PATHINFO_EXTENSION is the text after the last dot: archive.tar.gz has extension gz, not tar.gz. If your application treats compound suffixes as meaningful, define that convention separately.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Read the current request URL in PHP

When handling the request currently reaching your server, use the request target already provided by PHP:

$requestTarget = $_SERVER['REQUEST_URI'] ?? '';

REQUEST_URI contains the request path and query, for example /dev/website/shop-product.php?productID=1. If you need the final segment plus query, parse this value into path and query, then apply basename() to the path only. If you need the complete request target, use it directly; rebuilding a URL from host and scheme is unnecessary.

The PHP $_SERVER documentation describes values supplied by the server and execution environment. Do not treat request-derived values as trusted filesystem paths.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep URL parsing separate from file validation

  • A URL path can point to a rewritten route or controller rather than a physical file, so a visible filename or extension does not establish what the server returns.
  • A fragment beginning with # is separate from path and query. It is not part of the normal HTTP request target sent to the server.
  • Keep percent escapes when exact URL representation matters. Decode only for a defined application need; decoding is not validation and can change how separators are interpreted.
  • For uploads, remote files, or filesystem operations, a filename extension is untrusted input and does not prove a file’s type or safety. Validate based on the operation you intend to perform.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.