I am urlencoding a url string using php and then passing it via curl to a phantomjs script where I am trying to decode it using javascript.
I am starting with:
localhost:7788/hi there/how are you/
which gets turned into:
localhost:7788/hi+there%2Fhow+are+you
on the php side by the urlencode() function.
On the phantomjs side , I have:
// Create serever and listen port
server.listen(port, function(request, response) {
function urldecode(str) {
return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}
// Print some information Just for debbug
console.log("We got some requset !!!");
console.log("request method: ", request.method); // request.method POST or GET
console.log("Get params: ", request.url); //
url= urldecode(request.url);
//-- Split requested params
var requestparams = request.url.split('/');
console.log(urldecode(requestparams[1]));
console.log(urldecode(requestparams[2]));
The output at the console is :
.....
request method: GET
Get params: /hi%2Bthere/how%2Bare%2Byou
hi+there
how+are+you
Why are the '+' signs not replaced with spaces? I'm trying to get rid of them and it looks to me that the function 'urldecode' should do this.
You should use rawurlencode()
instead of urlencode()
in the PHP side, so spaces are encoded with %20
and not+
signs, so javascript can decode them well with decodeURIComponent()
.