How to correctly url-encode text across php and javascript
Hello !
So you have came to me again to seek invaluable tech tips on head-cracking problems. You did well and I was expecting you... please read below the answer to your much-awaited question.
To correctly encode extended characters in JavaScript and PHP, and decode them, and re-encode them while preserving every details without degradation, you need to have exact symmetric encoding / decoding. This can be a problem when it is different libraries doing these operations. Don't just guess it will work and hope nobody complains, use this time-tested solution :
JavaScript :
// RFC 3986 (which reserves !, ', (, ), and *)
function encodeURIComponentRFC3986(str)
{
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
To decode: decodeURIComponent()
PHP:
Note : With php version 5.3.0 and above.
To encode : rawurlencode()
From the php doc <<URL-encode according to RFC 3986>> -- http://php.net/manual/en/function.rawurlencode.php
To decode : rawurldecode()
More bed-time reading : http://www.faqs.org/rfcs/rfc3986.html
Recent Comments