1

I've been looking for the functions [used to encode and decode URL] that can be exchangable between PHP and Javascript [I can encode the URL in javascript and decode it in PHP and vice versa], there are many solutions come up, like escape() and unescape(); encodeURI() and decodeURI() for javascript, or urlencode() and urldecode() for PHP, but there is no pair which can works together perfectly. Because I want to send post data using Ajax jQuery for a PHP page to use, and data can be mixed with special character, that's why I need a function that works the same in PHP and Javascript:

Example:

$.ajax{url: "test.php", data: "http://www.thisURLContainSpecialCharac.ter"}

See the code above? It contains special characters in data, that may cause problem.

I appreciate any advice :). Thanks. [x]

1 Answer 1

1

You don't want to use Javascript's escape function since it does not URL encode. See http://xkr.us/articles/javascript/encode-compare/ for examples where it fails.

Javascript's encodeURIComponent will encode assuming UTF-8, so if you use that and make sure that your request has a content-type of UTF-8, you should be able to decode in PHP using

utf8_decode(urldecode($yourString)).

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

11 Comments

How are you sending data? Are you passing it in a GET URL, or in a POST message body?
@xx3004, I can't give you an example without knowing what you're doing. There seems to be a typo in "but I it works both ways". Could you please clarify.
@xx3004, JavaScript can encode special characters passed to a JavaScript function. JavaScript does not sit between the browser URL bar and your system though. The browser should make sure that only well-formed URLs reach your server, but you should not rely on it doing so.
What is it, and what is it sending to whom? If it is the user sitting at their browser in the URL bar, then you have no control about what they enter so don't worry. If it is some JavaScript code that you wrote, running in the server, then worry about it by using encodeURIComponent. Regardless of what is sending the message, your server code always needs to check that messages it receives are well-formed and authorized.
If the post body has the content type header set to application/x-www-form-urlencoded then PHP should automatically decode it. If the content is sent via the query part of the URL as part of a GET or POST request, then again, PHP should automatically decode it. The only time you need to decode is when you are using a funky content-type with a POST body.
|

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.