What's the PHP Equivalent of JavaScript decodeURIcomponent() Function?

The closest PHP equivalent of the JavaScript decodeURIComponent() function is the rawurldecode() function. However, you could also use the PHP urldecode() function. The difference between the two is in the way they decode literal plus sign (i.e. "+") present in the URL query string:

  • urldecode() will decode + into a space character;
  • rawurldecode() (as well as the JavaScript decodeURIComponent()) will not decode the + sign into any other character.

For example:

decodeURIComponent('+') === '+'; // true
<?php

rawurldecode('+') === '+'; // true
<?php

urldecode('+') === ' '; // true

Both PHP functions are valid and have their use cases. Therefore, depending on your use case you can choose either one.

Please note that you do not need to explicitly use urldecode() on $_GET and $_REQUEST array elements, as they're automatically decoded by PHP.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.