Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

encodeURI() in PHP?

Tags:

url

php

Is there some encodeURI() function in PHP that does not encode: ~!@#$&*()=:/,;?+'?

like image 720
fatalSc Avatar asked Feb 08 '11 04:02

fatalSc


People also ask

What is the use of encodeURI?

encodeURI and encodeURIComponent are used to encode Uniform Resource Identifiers (URIs) by replacing certain characters by one, two, three or four escape sequences representing the UTF-8 encoding of the character.

What is encodeURI component?

The encodeURIComponent() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

How encrypt URL in PHP?

PHP | urlencode() Function. The urlencode() function is an inbuilt function in PHP which is used to encode the url. This function returns a string which consist all non-alphanumeric characters except -_. and replace by the percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs.

What is the return value of encodeURI?

Return valueA new string representing the provided string encoded as a URI.


2 Answers

I'm using this now

function encodeURI($url) {     // http://php.net/manual/en/function.rawurlencode.php     // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURI     $unescaped = array(         '%2D'=>'-','%5F'=>'_','%2E'=>'.','%21'=>'!', '%7E'=>'~',         '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')'     );     $reserved = array(         '%3B'=>';','%2C'=>',','%2F'=>'/','%3F'=>'?','%3A'=>':',         '%40'=>'@','%26'=>'&','%3D'=>'=','%2B'=>'+','%24'=>'$'     );     $score = array(         '%23'=>'#'     );     return strtr(rawurlencode($url), array_merge($reserved,$unescaped,$score));  } 

It basically rawurlencodes everything, and then decodes a few things back (as Zanlok suggested in his comment). This should conform to the Mozilla specs of encodeURI.

And following MDN, 'if one wishes to follow the more recent RFC3986 for URLs', add

function fixedEncodeURI($url) {     return strtr(encodeURI($url),array('%5B'=>'[', '%5D'=>']')); } 
like image 160
commonpike Avatar answered Sep 21 '22 05:09

commonpike


Here's an alternate version based on ECMA-262 spec:

function encodeURI($uri) {     return preg_replace_callback("{[^0-9a-z_.!~*'();,/?:@&=+$#-]}i", function ($m) {         return sprintf('%%%02X', ord($m[0]));     }, $uri); } 
like image 23
Paulo Freitas Avatar answered Sep 22 '22 05:09

Paulo Freitas