Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript encodeURIComponent vs PHP ulrencode

The difference between them is that the PHP's urlencode encodes spaces with + instead of %20?

What are the functions that do the same thing for both the languages?

like image 518
Sandro Antonucci Avatar asked Sep 04 '11 15:09

Sandro Antonucci


3 Answers

Use rawurlencode instead of urlencode in PHP.

like image 167
cutsoy Avatar answered Sep 28 '22 01:09

cutsoy


Follow this link at php's own documention rawurlencode

rawurlencode will do the trick, the link is for reference.

like image 38
Pawan Choudhary Avatar answered Sep 28 '22 01:09

Pawan Choudhary


Actually even with JavaScript encodeURIComponent and PHP rawurlencode, they are not exactly the same too, for instance the '(' character, JavaScript encodeURIComponent will not convert it however PHP rawurlencode will convert it to %28. After some experiments and tips from others such as this question another Stackoverflow question.

I found the ultimate solution here.

All you need to do is use the add following code

function fixedEncodeURIComponent(str) {
    return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
        return '%' + c.charCodeAt(0).toString(16);
    });
}

They will be EXACTLY the same now, for example

fixedEncodeURIComponent(yourUrl) (JavaScript) = (PHP) rawurlencode(yourUrl)

no problem with decode, you can use decodeURIComponent() for JavaScript and rawurldecode for PHP

like image 37
Phantom1412 Avatar answered Sep 28 '22 01:09

Phantom1412