Getting the URL Without the Querystring
When constructing URLs for the current page using PHP, you might encounter instances where the requested URL includes a querystring, such as:
www.example.com/myurl.html?unwantedthngs
To remove the querystring and obtain a clean URL like:
www.example.com/myurl.html
you can leverage the versatile strtok function.
$url = strtok($_SERVER["REQUEST_URI"], '?');
strtok() provides a straightforward method for extracting the portion of the URL before the first occurrence of the ? character. In contrast to explode(), which necessitates creating an array with a maximum of two elements and then extracting the first element, strtok() is a more direct approach.
Using other methods, such as strstr() or substr(), may result in erratic behavior, particularly when the querystring is absent or contains multiple query parameters. To illustrate the effectiveness of strtok(), consider the following demonstration:
$urls = [ 'www.example.com/myurl.html?unwantedthngs#hastag', 'www.example.com/myurl.html' ]; foreach ($urls as $url) { var_export(['strtok: ', strtok($url, '?')]); echo "\n"; var_export(['strstr/true: ', strstr($url, '?', true)]); // unreliable echo "\n"; var_export(['explode/2: ', explode('?', $url, 2)[0]]); // limit stops after first encounter echo "\n"; var_export(['substr/strrpos: ', substr($url, 0, strrpos( $url, "?"))]); // unreliable echo "\n---\n"; }
Output:
array ( 0 => 'strtok: ', 1 => 'www.example.com/myurl.html', ) array ( 0 => 'strstr/true: ', 1 => 'www.example.com/myurl.html', ) array ( 0 => 'explode/2: ', 1 => 'www.example.com/myurl.html', ) array ( 0 => 'substr/strrpos: ', 1 => 'www.example.com/myurl.html', ) --- array ( 0 => 'strtok: ', 1 => 'www.example.com/myurl.html', ) array ( 0 => 'strstr/true: ', 1 => false, // unreliable ) array ( 0 => 'explode/2: ', 1 => 'www.example.com/myurl.html', ) array ( 0 => 'substr/strrpos: ', 1 => '', // unreliable ) ---
As seen in the output, strtok consistently returns the desired URL without the querystring, regardless of whether the querystring is present or empty. By using strtok(), you can effectively and reliably extract the clean URL from any given request.
The above is the detailed content of How Can I Efficiently Remove Query Strings from URLs in PHP?. For more information, please follow other related articles on the PHP Chinese website!