keepcalculator

06 Numbers and Powers

Get URL Filename Extension & Query String in PHP

Card No. 06·49546 · Updated · Standard formula, shown below

This guide shows you how to extract the filename extension and query string from a URL using PHP. You’ll learn reliable methods using built-in functions like parse_url(), pathinfo(), and basename(), plus how to handle edge cases like URLs without extensions or with complex query parameters. No special libraries are needed—just a working PHP environment (PHP 5.4+ recommended).

What You’ll Need

  • A PHP-enabled web server or local PHP installation (e.g., XAMPP, MAMP, or the php CLI).
  • A text editor or IDE to write the code.
  • Basic familiarity with PHP syntax and functions.

Step-by-Step

  1. Start with a sample URL – Use a variable to hold the URL you want to parse. For example: $url = 'https://example.com/images/photo.jpg?size=large&mode=edit';
  2. Break the URL into parts – Use parse_url() to split the URL into its components (scheme, host, path, query, etc.). This function returns an associative array.
  3. Get the path part – From the parsed array, access $parts['path'] to get the path component (e.g., /images/photo.jpg). If the URL has no path, this key may be missing—check with isset().
  4. Extract the filename – Use basename($path) to get the last segment of the path, which is the filename (e.g., photo.jpg).
  5. Get the extension – Feed the filename to pathinfo($filename, PATHINFO_EXTENSION) to get just the extension (e.g., jpg). If the filename has no dot, pathinfo() returns an empty string.
  6. Get the query string – From the parsed array, access $parts['query'] to get the query string (e.g., size=large&mode=edit). If the URL has no query, this key is missing—handle that with a fallback.
  7. Put it all together – Write a small function that takes a URL and returns an array with extension and query. Here’s a complete example:
<?php
function getUrlParts($url) {
    $parts = parse_url($url);
    $path = isset($parts['path']) ? $parts['path'] : '';
    $filename = basename($path);
    $extension = pathinfo($filename, PATHINFO_EXTENSION);
    $query = isset($parts['query']) ? $parts['query'] : '';
    return ['extension' => $extension, 'query' => $query];
}

$url = 'https://example.com/images/photo.jpg?size=large&mode=edit';
$result = getUrlParts($url);
echo 'Extension: ' . $result['extension'] . "\n"; // jpg
echo 'Query: ' . $result['query'] . "\n"; // size=large&mode=edit
?>

Common Mistakes

  • Forgetting to check for missing keys – parse_url() returns only the components present in the URL. Accessing $parts['query'] without checking will trigger a notice in PHP 7.4+ or a warning in PHP 8. Always use isset() or the null coalescing operator (??).
  • Using pathinfo() on the full URL – If you pass the full URL (including query string) to pathinfo(), the extension will be wrong because the query string becomes part of the filename. Always extract the path first.
  • Assuming every URL has a dot in the filename – URLs like /about have no extension. Your code should handle that gracefully (returns empty string).
  • Ignoring URL-encoded characters – Query strings may contain percent-encoded characters (e.g., %20 for space). If you need the decoded version, use urldecode() or parse_str().

Tips

  • Use pathinfo() with PATHINFO_FILENAME – If you also need the filename without the extension, use pathinfo($filename, PATHINFO_FILENAME).
  • Handle query parameters as an array – For easier access, use parse_str($query, $params) to turn the query string into an associative array.
  • Consider the fragment – parse_url() also returns the fragment (after #). If you need it, access $parts['fragment'].
  • Test with various URLs – Try URLs with no path, no query, or with a trailing slash to ensure your function behaves as expected.

Troubleshooting

  • Getting an empty extension – This usually means the URL has no dot in the filename, or the path is empty. Check the URL manually. If the URL uses a query string that contains a dot (e.g., ?file=image.jpg), remember that the query is not part of the path.
  • Notice: Undefined index: query – This happens when the URL has no query string. Use isset() or ?? '' to avoid it.
  • Extension includes a query string – This occurs when you pass the full URL to pathinfo(). Always use parse_url() first to isolate the path.
  • URL contains special characters – If the URL has spaces or non-ASCII characters, they may be encoded. Use rawurldecode() on the path if you need the original characters.

Frequently Asked Questions

What if the URL has no extension?

If the path has no dot, pathinfo() returns an empty string. That’s fine—your code should handle it gracefully, e.g., by setting a default value.

How do I get the query parameters as an array?

Use parse_str($query, $params) after extracting the query string. This gives you an associative array where keys are parameter names and values are their values.

Can I use this on the current page URL?

Yes, use $_SERVER['REQUEST_URI'] to get the current URL path and query string. For example: $url = $_SERVER['REQUEST_URI'];

What about URLs with ports or user info?

parse_url() handles those components, but they don’t affect the path or query. The function will still correctly extract the extension and query.

Is there a way to get the extension without using pathinfo()?

You can use strrchr() and substr() to find the last dot, but pathinfo() is more reliable and handles edge cases like hidden files (e.g., .htaccess).

Does this work with relative URLs?

Yes, parse_url() works with relative URLs like /images/photo.jpg?size=small. The path and query are extracted the same way.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →