Current Location: Home> Latest Articles> How to use parse_url and pathinfo to analyze the path and file structure of a URL?

How to use parse_url and pathinfo to analyze the path and file structure of a URL?

gitbox 2025-05-26

parse_url is a built-in function in PHP that parses URLs and returns their components, such as protocols, host names, paths, query strings, etc.

 $url = "https://gitbox.net/path/to/file.php?query=123";

$parsedUrl = parse_url($url);
print_r($parsedUrl);

The output will be an associative array:

 Array
(
    [scheme] => https
    [host] => gitbox.net
    [path] => /path/to/file.php
    [query] => query=123
)

With parse_url we can easily get the path part in the URL.

2. Introduction to pathinfo function

pathinfo is a function used to parse file path information. It returns information such as directory name, file name and extension of the file.

Continuing with the above example, we can use it like this:

 $path = $parsedUrl['path']; // /path/to/file.php

$fileInfo = pathinfo($path);
print_r($fileInfo);

Output:

 Array
(
    [dirname] => /path/to
    [basename] => file.php
    [extension] => php
    [filename] => file
)

This allows us to easily get the file name and extension, or the directory path we are in.

3. Comprehensive examples

Here is an example combining parse_url and pathinfo to demonstrate how to extract the path and file information of the URL:

 <?php

$url = "https://gitbox.net/path/to/file.php?query=123";

// AnalysisURL
$parsedUrl = parse_url($url);

// Take out the path part
$path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';

// usepathinfoAnalysis路径
$fileInfo = pathinfo($path);

// Output result
echo "Complete path: " . $path . PHP_EOL;
echo "Directory name: " . ($fileInfo['dirname'] ?? '') . PHP_EOL;
echo "file name: " . ($fileInfo['basename'] ?? '') . PHP_EOL;
echo "Extension: " . ($fileInfo['extension'] ?? '') . PHP_EOL;
echo "不带Extension的file name: " . ($fileInfo['filename'] ?? '') . PHP_EOL;

Running results:

 Complete path: /path/to/file.php
Directory name: /path/to
file name: file.php
Extension: php
不带Extension的file name: file

4. Summary

  • parse_url is used to parse URLs and extract components such as protocol, host, path, query, etc.

  • pathinfo is used to parse file paths and extract information such as directories, file names, extensions, etc.

  • Combined use can easily analyze the path and file structure in the URL, which is suitable for path judgment, file processing, routing analysis and other scenarios.

Mastering these two functions can greatly improve your efficiency and accuracy of URL and path processing.

  • Related Tags:

    URL