pear/net_url2
PEAR Net_URL2 is a small PHP utility for parsing, validating, and manipulating URLs. It builds and edits URL components, handles query strings, resolves relative URLs, and offers easy getters/setters for scheme, host, path, port, user info, and fragments.
Installation
composer require pear/net_url2
Add to composer.json if not using autoloading globally:
"autoload": {
"psr-4": {
"App\\": "app/"
}
}
Run composer dump-autoload.
First Use Case Parse a URL into components:
use Net_URL2;
$url = new Net_URL2('https://example.com/path/to/resource?query=value#fragment');
$parsed = $url->getParts();
// Returns associative array: ['scheme', 'host', 'path', 'query', 'fragment', ...]
Where to Look First
Net/URL2.php (check for methods like getParts(), setParts(), get(), set()).Parsing and Reconstructing URLs
$url = new Net_URL2('https://user:[email protected]:8080/path?query=1#frag');
$parts = $url->getParts(); // Extract components
$reconstructed = $url->get(); // Rebuild URL string
Handling Relative URLs Resolve relative paths against a base URL:
$base = new Net_URL2('https://example.com/base/');
$relative = new Net_URL2('subpath');
$absolute = $base->resolve($relative); // 'https://example.com/base/subpath'
Query String Manipulation Parse/modify query parameters:
$url = new Net_URL2('https://example.com?foo=bar&baz=qux');
$query = $url->getQuery(); // ['foo' => 'bar', 'baz' => 'qux']
$url->setQuery(['foo' => 'updated']); // Updates query string
Validation and Sanitization Check URL validity or enforce schemes/hosts:
if ($url->isValid()) {
// Proceed
}
$url->setScheme('https'); // Enforce HTTPS
$requestUrl = new Net_URL2(request()->getRequestUri());
$queryParams = $requestUrl->getQuery();
$apiUrl = new Net_URL2('https://api.example.com/v1');
$resourceUrl = $apiUrl->resolve('/users/123');
return response()->json(['url' => $resourceUrl->get()]);
$url = new Net_URL2($request->url());
if (!$url->getPath() || substr($url->getPath(), -1) !== '/') {
return redirect($url->setPath($url->getPath() . '/')->get());
}
Case Sensitivity in Schemes/Hosts
HTTP vs http) and hosts may be case-sensitive in parsing. Use strtolower() if consistency is critical:
$url->setScheme(strtolower($url->getScheme()));
Query String Encoding
$encoded = urlencode($value); // Before setting query
$decoded = urldecode($query['param']); // After getting query
Fragment Handling
#fragment) are parsed but may not be preserved in all operations. Test edge cases:
$url = new Net_URL2('https://example.com#test');
$url->setPath('/new-path'); // Fragment may be lost; re-add if needed
Port Omission
80 for HTTP) may not be included in output. Explicitly set if needed:
$url->setPort(80); // Force inclusion
Relative Path Resolution
../parent) are resolved against the base URL, but edge cases (e.g., ../../../) may behave unexpectedly. Validate paths:
$resolved = $base->resolve($relative);
if (strpos($resolved->getPath(), '../') !== false) {
throw new \InvalidArgumentException('Invalid relative path');
}
dd($url->getParts()); // Full breakdown of URL parts
array_key_first() may not work; use array_keys() instead).Custom Validation Extend with a validator trait or class:
class ValidatedURL extends Net_URL2 {
public function validate() {
if (empty($this->getHost())) {
throw new \InvalidArgumentException('Host is required');
}
return true;
}
}
Hooks for Pre/Post-Operations
Override methods like setParts() to add logic:
class HookedURL extends Net_URL2 {
public function setParts(array $parts) {
$parts['scheme'] = strtolower($parts['scheme'] ?? '');
return parent::setParts($parts);
}
}
Integration with Laravel URL Helper
Create a facade or helper to wrap Net_URL2:
// app/Helpers/UrlHelper.php
function parseUrl(string $url): array {
$netUrl = new Net_URL2($url);
return $netUrl->getParts();
}
How can I help you explore Laravel packages today?