Javascript's “unescape” in PHP

放肆的年华 提交于 2019-12-23 22:09:12

问题


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?


回答1:


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.




回答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"])


来源:https://stackoverflow.com/questions/14364496/javascripts-unescape-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!