1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| <?php
$allowedDomains = array( "aaaa.com" "bbbb.com" ....... ); function encodeUrl($urlInfo) { $path = isset($urlInfo['path']) ? $urlInfo['path'] : ''; if(!empty($path)) { $t = explode("/", $path); for($i = 0; $i < count($t); $i++) { $t[$i] = rawurlencode($t[$i]); } $path = implode("/", $t); } $query = isset($urlInfo['query']) ? $urlInfo['query'] : ''; if(!empty($query)) { $t = explode("&", $query); for($i = 0; $i < count($t); $i++) { $tt = explode("=", $t[$i]); $tt[1] = rawurlencode($tt[1]); $t[$i] = implode("=", $tt); } $query = implode("&", $t); } if(!isset($urlInfo['host']) || empty($urlInfo['host'])) { return $path. "?". $query; } $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : 'http'; $port = isset($urlInfo['port']) ? $urlInfo['port'] : 80; $request = $scheme . '://'. $urlInfo['host']; $request .= ($port == 80) ? '' : ':'.$port; $request .= $path; $request .= (empty($query)) ? '' : '?'.$query; return $request; } function checkUrl($url,$domainArr=array()) { $res = array('isTrustedDomain' => false,'url' => '','domain' => ''); if(empty($url)) return $res; $domainArr = empty($domainArr) || !is_array($domainArr) ? $allowedDomains : $domainArr; $url = filterUrl($url); $p = parse_url($url); $scheme = $p['scheme']; if(!in_array(strtolower($scheme),array('http','https'))){ return $res; } $host = $p['host']; if(!isValidHost($host)){ return $res; } $hostLen = strlen($host); foreach($domainArr as $domain){ $firstPos = strpos($host, $domain); if($firstPos !== false && ($firstPos + strlen($domain)) == $hostLen){ if($firstPos == 0 || $domain[0] == '.' || $host[$firstPos-1] == '.'){ $res['isTrustedDomain'] = true; $res['url'] = $url; $res['domain'] = $domain; break; } } } return $res; } function filterUrl( $url ) { if(empty($url)) return $url; $url = preg_replace('/<SCRIPT.*?<\/SCRIPT>/ims',"",$url); $url = preg_replace('/[\s\v\0]+/',"",$url); $url = str_replace(array("'","\"","<",">","\\"),'',$url); return $url; } function isValidHost($host) { $p = "/^[0-9a-zA-Z\-\.]+$/"; return preg_match($p,$host) ? true : false; } $url = "https://www.baidu.com"; $call_back_url = trim($url); $call_back_url = encodeUrl(parse_url(urldecode($call_back_url))); $res = checkUrl($call_back_url, $domainArr); var_dump($res);
|