上一篇
PHP 简易过滤上传多媒体文件
Iframe一个不受限制随时随地的引用外部网站的标签,瞬间可以将主页填充起来的小技巧。举个例子:在2009年前后,手机线上充值业务处于山头林立时期,得益于程序员将手机充值服务封装成iframe小挂件。
ConsoleUncaught DOMException: Blocked a frame with origin "http://www.didaolan.cn" from accessing a cross-origin frame.
抛开对SEO不友好外,Iframe是一个很实在的标签。可欲望是无止境,Iframe原原本本的引入网站,容易让人产生一个大胆的想法:修改iframe的内容。
想通过Jquery选择器修改Iframe的内容,现实狠狠给了一巴掌:Iframe不充许跨域进行操作。上有对策,下有政策。通过服务端使用file_get_contents函数,直接将网页的HTML数据拖回本地,绕过跨域限制。
PHP$url = 'https://www.didaolan.cn/index.html';
$html = file_get_contents($url);
print_r($html);
你以为事情到此为止了吗?然而这只是另一个麻烦的开端。网站同属中文网站阵营,然而使用的字符集包括有GBK、GB2312和UTF-8,导致file_get_contents抓包后出现中文乱码。对于中文乱码现象,可使用iconv进行字符集转义。
旧的问题解决,新的问题又产生了,怎么判断网站是否需要转义?最初使用mb_detect_encoding来判断字符集,可是效果不太理想,最后只能通过逐个逐个字付的ASCII值来判断。
PHP/**
* 是否UTF-8字符集
* @method isUtf8
* @param $str 字符串
* @return bool
*/
function isUtf8($str){
$len = strlen($str);
for($i = 0; $i < $len; $i++){
$c = ord($str[$i]);
if ($c > 128) {
if (($c > 247)) {
return false;
} else if ($c > 239) {
$bytes = 4;
} else if ($c > 223) {
$bytes = 3;
} else if ($c > 191) {
$bytes = 2;
} else {
return false;
}
if (($i + $bytes) > $len) {
return false;
}
while ($bytes > 1) {
$i++;
$b = ord($str[$i]);
if ($b < 128 || $b > 191) {
return false;
}
$bytes--;
}
}
}
return true;
}
几经周折,最终Iframe跨域引用需要通过中间层处理,Jquery才能顺利使用选择器。
PHP$url = 'https://www.didaolan.cn/index.html';
$html = file_get_contents('compress.zlib://'.$url);
if(isUtf8($html) != 1) { //非UTF-8字符集转义
$html = iconv("GB2312", "UTF-8//IGNORE",$html);
}
print_r($html);
※ iconv字符集转码不是100%转码成功,如果字符串又包含特殊字符集,特殊字符集有机率出现中文乱码。
最新评论Latest comments