Special Anniversary Black Friday: Get 30% off all training and 10% off all services Get a Quote


PHP 8.5's New URI Extension: A Game-Changer for URL Parsing

· Oskar Stark · 3 minutes to read
PHP 8.5 URI extension

PHP 8.5 introduces a powerful new URI extension that modernizes URL handling. With support for both RFC 3986 and WHATWG standards, the new Uri class provides immutable objects, fluent interfaces, and proper validation - addressing all the limitations of the legacy parse_url() function. This guide shows practical before/after examples and explains when to use each standard.

The Problem with parse_url()

For years, PHP developers have relied on parse_url() for URL parsing. While functional, it has several limitations:

$url = 'https://api.example.com:8080/users?id=123&sort=name#profile';
$parts = parse_url($url);

echo $parts['scheme'];    // https
echo $parts['host'];      // api.example.com
echo $parts['port'];      // 8080
echo $parts['path'];      // /users
echo $parts['query'];     // id=123&sort=name
echo $parts['fragment'];  // profile

Key limitations:

  • Returns an associative array rather than an object

  • Limited validation capabilities

  • No built-in URL building or modification methods

  • Inconsistent handling of edge cases

  • No support for modern URL manipulation patterns

Introducing the Uri Classes

PHP 8.5's new URI extension provides two standards-compliant implementations:

use Uri\Rfc3986\Uri;

$uri = new Uri('https://api.example.com:8080/users?id=123&sort=name#profile');

echo $uri->getScheme();    // https
echo $uri->getHost();      // api.example.com
echo $uri->getPort();      // 8080
echo $uri->getPath();      // /users
echo $uri->getQuery();     // id=123&sort=name
echo $uri->getFragment();  // profile

Available implementations:

  • Uri\Rfc3986\Uri - For RFC 3986 compliant URI parsing (general-purpose URIs)

  • Uri\WhatWg\Url - For WHATWG URL standard (browser-compatible URLs)

Both classes offer:

  • Immutable URL objects with getter and setter methods

  • Standards-compliant parsing (RFC 3986 or WHATWG)

  • Fluent interface for URL manipulation

  • Better error handling and validation

  • Built-in support for URL building and modification

Building and Modifying URLs

One of the most powerful features is the fluent interface for URL manipulation:

Before:

$url = 'https://example.com/api/v1/users';
$parts = parse_url($url);

// Adding query parameters requires manual work
$parts['query'] = 'page=2&limit=20';

// Rebuilding the URL is tedious
$newUrl = $parts['scheme'] . '://' . 
          $parts['host'] . 
          $parts['path'] . 
          '?' . $parts['query'];

echo $newUrl; // https://example.com/api/v1/users?page=2&limit=20

After:

use Uri\Rfc3986\Uri;

$uri = new Uri('https://example.com/api/v1/users');

// Fluent interface makes modifications elegant
$newUri = $uri
    ->withQuery('page=2&limit=20')
    ->withFragment('results');

echo $newUri->toString(); 
// https://example.com/api/v1/users?page=2&limit=20#results

Changing URL Components

The immutable nature of Uri objects makes component changes safe and predictable:

Before:

$url = 'http://example.com/old-path';
$parts = parse_url($url);

// Manual reconstruction for every change
$parts['scheme'] = 'https';
$parts['path'] = '/new-path';
$parts['query'] = 'updated=true';

$newUrl = $parts['scheme'] . '://' . 
          $parts['host'] . 
          $parts['path'] . 
          '?' . $parts['query'];

echo $newUrl; // https://example.com/new-path?updated=true

After:

use Uri\Rfc3986\Uri;

$uri = new Uri('http://example.com/old-path');

$newUri = $uri
    ->withScheme('https')
    ->withPath('/new-path')
    ->withQuery('updated=true');

echo $newUri->toString(); // https://example.com/new-path?updated=true

Key Benefits

1. Type Safety and IDE Support

The Uri class provides full type hints and autocomplete support in modern IDEs, making development faster and less error-prone.

2. Immutability

Each modification returns a new Uri instance, preventing unintended side effects and making code more predictable.

3. Better Validation

The Uri class validates URLs during construction and modification, catching errors early rather than producing malformed URLs.

4. RFC Compliance

Full compliance with RFC 3986 ensures consistent behavior across different URL formats and edge cases.

5. Normalized and Raw Output

The Uri class provides both normalized and raw output methods, giving you control over URL representation:

use Uri\Rfc3986\Uri;

$uri = new Uri('HTTPS://thephp.foundation:443/sp%6Fnsor/');

echo $uri->toString();    
// https://thephp.foundation/sponsor/ (normalized)

echo $uri->toRawString(); 
// HTTPS://thephp.foundation:443/sp%6Fnsor/ (raw input preserved)

Migration Tips

While the Uri class is superior for new code, you don't need to rush to update existing parse_url() calls. Consider using the Uri class for:

  • New projects and features

  • Code that frequently manipulates URLs

  • APIs that work with complex URL structures

  • Situations requiring strict URL validation

  • When you need to choose between RFC 3986 and WHATWG standards

Choosing Between RFC 3986 and WHATWG

Use Uri\Rfc3986\Uri when:

  • Working with general-purpose URIs (FTP, file, custom schemes)

  • You need RFC 3986 compliance for backend services

  • Parsing non-web URIs

Use Uri\WhatWg\Url when:

  • Building web applications that interact with browsers

  • You need browser-compatible URL parsing

  • Working with HTTP/HTTPS URLs that users will see

Performance Considerations

The Uri class has minimal performance overhead compared to parse_url(). For most applications, the benefits far outweigh any negligible performance difference. If you're parsing millions of URLs per second, benchmark your specific use case.

Conclusion

PHP 8.5's URI extension represents a significant step forward in URL handling. The new URI classes (Uri\Rfc3986\Uri and Uri\WhatWg\Url) provide modern, standards-compliant approaches that make URL parsing, manipulation, and validation more intuitive and reliable.

Whether you're building APIs, web scrapers, or any application that works with URLs, the URI extension will make your code cleaner and more maintainable. Best of all, it's bundled directly with PHP 8.5 - no extra installation required!

Start exploring the URI extension in your PHP 8.5 projects today, and experience the difference that proper URL handling can make!

Official Resources

Important: The URI extension is bundled with PHP 8.5 and always available - no separate installation or ext-urirequirement needed!

Sources

Note: The URI extension is available in PHP 8.5+ and is bundled by default. Make sure your environment is updated before using these features.

Want to Gain More Knowledge?

SensioLabs has customizable training sessions to help you and your team master PHP 8.5's new features, including the URI extension and other modern PHP best practices.

This might also interest you

Open in new tab
Silas Joisten

The Tab Trap: Why Forcing New Tabs Is Bad UX

We’ve all done it — added target="_blank" to a link to “help users” stay on our site. But what feels like a harmless convenience often creates confusion, breaks accessibility, and introduces hidden security risks.

Read more
3 dog heads
Mathieu Santostefano

Bring Your Own HTTP client

Break free from rigid dependencies in your PHP SDKs. Learn how to use PSR-7, PSR-17, and PSR-18 standards along with php-http/discovery to allow users to bring their favorite HTTP client, whether it's Guzzle, Symfony HttpClient, or another. A must-read for PHP and Symfony developers.

Read more
Blue sign on a building with several Now What? letters
Thibaut Chieux

How To Prioritize Messages When Building Asynchronous Applications With Symfony Messenger

Asynchronous processing offers benefits like decoupled processes and faster response times, but managing message priorities can become a challenge. When dealing with tasks ranging from password resets to complex exports, ensuring timely delivery of critical messages is essential. This article explores common asynchronous processing issues and provides solutions using Symfony Messenger, allowing you to optimize your application without extensive refactoring.

Read more
PHP 8.5
Oskar Stark

What's New in PHP 8.5: A Comprehensive Overview

PHP 8.5 will be released in November 2025 and brings several useful new features and improvements. This version focuses on developer experience enhancements, new utility functions, and better debugging capabilities.

Read more
Two images: on the left many cars stuck in a traffic jam with the sign "All directions" above, on the right a blue car moving forward alone on the highway with the sign "Service Subscriber" and a Symfony logo above
Steven Renaux

Symfony Lazy Services with Style: Boost DX using Service Subscribers

Boost your Symfony app's performance and developer experience! Learn how to use Service Subscribers and traits for lazy service loading to reduce eager instantiation, simplify dependencies, and create modular, maintainable code.

Read more
the surface of the earth seen from the space with city lights forming networks
Imen Ezzine

HTTP Verbs: Your Ultimate Guide

HTTP Verbs Explained: Learn the basics of GET, POST, PUT, DELETE, and more. This article explains how they work, their applications, and their security implications.

Read more
Toy factory production line
Silas Joisten

Supercharging Symfony Testing with Zenstruck Foundry

Zenstruck Foundry has revolutionized the way we write tests in Symfony. In this post, you’ll learn how expressive factories, isolated test data, and a smoother developer experience helped us streamline our testing workflow and boost productivity.

Read more
Domain Driven Design practical approach
Silas Joisten

Applying Domain-Driven Design in PHP and Symfony: A Hands-On Guide

Learn how to apply Domain-Driven Design (DDD) principles in Symfony with practical examples. Discover the power of value objects, repositories, and bounded contexts.

Read more
Photo speaker meetup AI Symfony
Jules Daunay

Symfony and AI: the video is now available

What about Symfony and Artificial Intelligence (AI)? This was the theme of the exclusive event organized by SensioLabs in partnership with Codéin on October 3rd. With the added bonus of feedback from a development project combining Symfony and AI. If you missed the event, check out the video now available for free on our Youtube channel.

Read more
2025 a year of celebrations for PHP with windows about API Platform, PHP, AFUP and Symfony
Jules Daunay

2025: a year of anniversaries for PHP, AFUP, Symfony and API Platform

2025 is going to be a big year for anniversaries. We will be celebrating the 20th anniversary of Symfony, the 30th anniversary of PHP, the 25th anniversary of AFUP and the 10th anniversary of API Platform. For SensioLabs, this is a major milestone that proves the longevity of the technologies in our ecosystem. We are proud to celebrate these anniversaries with the community all year long.

Read more
Blue ElePHPant on a computer
Imen Ezzine

Optimize Your PHP Code: 8 Functions You Need for Efficient Table Handling

If you want to become a good PHP developer, you must learn to work with arrays. Arrays are used a lot in PHP: temporarily store, organize, and process data before it's saved in a database. Knowing how to work with them efficiently will help you manage and process data more effectively.

Read more
Grey Cargo Plane with a Blue Sky
Rémi Brière

Agility and the Cargo Cult - Part 1

Agility is more than just rituals and tools. In this first article of our Scrum series, we explore the Cargo Cult phenomenon and how blind imitation can hinder true Agile transformation.

Read more
SemVer vs. CalVer
Silas Joisten

SemVer vs. CalVer: Which Versioning Strategy is Right for You?

SemVer ensures stability for libraries, while CalVer aligns projects with release cycles. Learn the key differences and best use cases to optimize your versioning strategy.

Read more
Image of a desk with a laptop and monitor
Oskar Stark

Introducing PIE: The Modern PHP Extension Installer

Discover PIE, the new PHP Installer for Extensions, a modern tool that simplifies managing PHP extensions with a Composer-like workflow. Say goodbye to PECL complexities and streamline your development process with PIE.

Read more
DDD
Silas Joisten

Understanding Domain-Driven Design: A Practical Approach for Modern Software Architecture

Explore Domain-Driven Design (DDD) principles and patterns like Ubiquitous Language, Aggregates, and Bounded Contexts. Learn how DDD fits seamlessly into PHP and Symfony projects, helping you align software with business needs.

Read more
Image