PHP中的Javascript“unes​​cape”

时间:2013-01-16 17:45:05

标签: php javascript validation url hyperlink

我的图片主机有一个Google Chrome扩展程序,它会向我的网站发送一个网址。该网址通过Javascript的escape方法编码

escape编码的网址如下所示:

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

我需要通过PHP以某种方式将URL恢复正常,因此我可以针对filter_var($the_url, FILTER_VALIDATE_URL)进行检查,如果URL如上所述,它显然会失败。

这就是Javascript的样子:

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});

这就是我在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;
}

坦率地说,urldecode()并不适合我。您可以注意到,我通过$_GET收到了网址。

处理这种情况的最佳方法是什么?

实际问题:如何在PHP中 unescape 转义的网址?有没有更好的方法来处理这个问题?

2 个答案:

答案 0 :(得分:6)

您需要使用encodeURIComponent代替escape

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

然后,您可以在PHP中使用urldecode来获得所需的结果。

有关escapeencodeURIencodeURIComponent的解释,请参阅this question

答案 1 :(得分:1)

适用于Javascript发送:

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

在PHP代码中

$url = urldecode($_GET["my_url"])
相关问题