6

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?

4 Answers 4

20

Use rawurlencode instead of urlencode in PHP.

Sign up to request clarification or add additional context in comments.

2 Comments

Is that really the case though? PHP docs are confusing me... it says rawurlencode is for /.../ and urlencode is for /?....
This could be useful: the-art-of-web.com/javascript/escape. It's an online tool that lets you see how each function in both languages encode a URI. rawurlencode and encodeURIComponent produced the same output.
2

Follow this link at php's own documention rawurlencode

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

Comments

1

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

Comments

0

I was having the same problem between rawurlencode() and encodeURIComponent(). The difference for me was that I didn't discover the issue until using encodeURIComponent() in numerous source files, so going back to fix and change them all and then re-test everything was not an option.

Fortunately, JS gives you the ability to "hijack" built-in functions by assigning the same name to a new function. You can thus change the behavior of encodeURIComponent() with a very slight modification to Phantom1412's code, and without having to recode anything.

Just put this script in your page before your code makes any calls to encodeURIComponent():

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.