Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode a URL as a CakePHP parameter

I would like to create a bookmarklet for adding bookmarks. So you just click on the Bookmark this Page JavaScript Snippet in your Bookmarks and you are redirected to the page.

This is my current bookmarklet:

"javascript: location.href='http://…/bookmarks/add/'+encodeURIComponent(document.URL);"

This gives me an URL like this when I click on it on the Bookmarklet page:

http://localhost/~mu/cakemarks/bookmarks/add/http%3A%2F%2Flocalhost%2F~mu%2Fcakemarks%2Fpages%2Fbookmarklet

The server does not like that though:

The requested URL /~mu/cakemarks/bookmarks/add/http://localhost/~mu/cakemarks/pages/bookmarklet was not found on this server.

This gives the desired result, but is pretty useless for my use case:

http://localhost/~mu/cakemarks/bookmarks/add/test-string

There is the CakePHP typical mod_rewrite in progress, and it should transform the last part into a parameter for my BookmarksController::add($url = null) action.

What am I doing wrong?

like image 862
Martin Ueding Avatar asked Oct 11 '22 03:10

Martin Ueding


1 Answers

I had a similar problem, and tried different solutions, only to be confused by the cooperation between CakePHP and my Apache-config.

My solution was to encode the URL in Base64 with JavaScript in browser before sending the request to server.

Your bookmarklet could then look like this:

javascript:(function(){function myb64enc(s){s=window.btoa(s);s=s.replace(/=/g, '');s=s.replace(/\+/g, '-');s=s.replace(/\//g, '_');return s;} window.open('http://…/bookmarks/add/'+myb64enc(window.location));})()

I make two replacements here to make the Base64-encoding URL-safe. Now it's only to reverse those two replacements and Base64-decode at server-side. This way you won't confuse your URL-controller with slashes...

like image 61
poplitea Avatar answered Oct 18 '22 00:10

poplitea