2

I have a Google Chrome extension for my image host and it send an URL to my website. That URL gets encoded via Javascript's escape method.

An URL encoded by escape looks like this:

http%253A//4.bp.blogspot.com/-xa4Krfq2V6g/UF2K5XYv3kI/AAAAAAAAAJg/8wrqZQP9ru8/s1600/LuffyTimeSkip.png

I need to get the URL back to normal via PHP somehow, so I can check it against filter_var($the_url, FILTER_VALIDATE_URL) and it obviously fails if the URL is like above.

This is how the Javascript looks like:

function upload(img) {
    var baseurl="http://imgit.org/remote?sent-urls=1&remote-urls=" + escape(img.srcUrl);
    uploadImage(baseurl);
}
function uploadImage(imgurl) {
        chrome.tabs.create({
        url: imgurl,
        selected: true
    });
}

var title = "Upload this image to IMGit";
var id = chrome.contextMenus.create({"title": title, "contexts": ['image'], "onclick": upload});

And this is what I do in PHP:

if (!filter_var($file, FILTER_VALIDATE_URL) || !filter_var(urldecode($file), FILTER_VALIDATE_URL))
{
    throw_error('The entered URLs do not have a valid URL format.', 'index.php#remote'); break;
}

Frankly, urldecode() doesn't do the job for me. And as you can notice, I am receiving the URL via $_GET.

What would be the best way to handle this situation?

Actual question: How do I unescape the escaped URL in PHP? Is there a better way to handle this problem?

aborted
  • 4,481
  • 14
  • 69
  • 132
  • What's `$the_url`? Anything that comes from `$_GET` is decoded automatically. – NullUserException Jan 16 '13 at 17:48
  • Could you post what the url looks like after `urldecode` has run it? Also you may want to look into `encodeUri` as an alternative to `escape`. This [article](http://stackoverflow.com/questions/75980/best-practice-escape-or-encodeuri-encodeuricomponent) may be of some help. Be advised that depending on the receiving server, it may not be able to properly decode the way escape encodes upper ASCII or non-ASCII characters. – War10ck Jan 16 '13 at 17:50
  • In your `upload` function, if you `alert(img.srcUrl)`, do you get an already encoded url? – Lukas Jan 16 '13 at 18:04

2 Answers2

6

You'll want to use encodeURIComponent instead of escape:

function upload(img) {
    var baseurl="http://imgit.org/remote?sent-urls=1&remote-urls=" + encodeURIComponent(img.srcUrl);
    uploadImage(baseurl);
}

Then, you can use urldecode inside PHP to get the result you want.

See this question for an explanation of escape vs. encodeURI vs. encodeURIComponent.

Community
  • 1
  • 1
Lukas
  • 9,765
  • 2
  • 37
  • 45
2

For send in Javascript:

var baseurl="http://imgit.org/remote?sent-urls=1&remote-urls=" + encodeURIComponent(img.srcUrl);

In PHP code

$url = urldecode($_GET["my_url"])
regisls
  • 529
  • 6
  • 23