Home >Backend Development >PHP Tutorial >How Can I Remove Query Strings from URLs in PHP to Get Clean URLs?

How Can I Remove Query Strings from URLs in PHP to Get Clean URLs?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-02 20:47:11797browse

How Can I Remove Query Strings from URLs in PHP to Get Clean URLs?

Removing Querystring for Clean URLs

In PHP, URLs often include querystrings that contain additional information. However, sometimes you may need to retrieve only the clean URL without the querystring.

PHP Implementation

To accomplish this, you can employ the strtok() function:

$url = strtok($_SERVER["REQUEST_URI"], '?');

strtok() efficiently captures the string before the first occurrence of the ?.

Additional Techniques

While strtok() is the recommended approach, there are alternative techniques:

  • strstr(): Captures the string before the ? if used with true as the second argument. However, it's less reliable.
  • explode(): Splits the URL into an array at the ?. Access the first element for the clean URL.
  • substr(): Combined with strrpos(), this method also has reliability issues.

Demonstration

To illustrate the different techniques, consider the following URLs:

  • www.example.com/myurl.html?unwantedthngs
  • www.example.com/myurl.html

The output of the different methods is as follows:

Method Output
strtok() www.example.com/myurl.html
strstr(/true) www.example.com/myurl.html
explode(/2) www.example.com/myurl.html
substr/strrpos() www.example.com/myurl.html

As you can see, strtok() consistently provides the correct result, while the other techniques may fail in certain cases, especially when the querystring is missing.

The above is the detailed content of How Can I Remove Query Strings from URLs in PHP to Get Clean URLs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn