龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

相对路径 转 网络绝对路径(支持二级域名) ./a.j

时间:2014-07-22 14:48来源: 作者: 点击:
分享到:
昨天在写用迅雷下载时,发现 ./a.jpg的文件转成迅雷不是网络地址,然后写了一个方法转换。目前处在PHP基础层次,有不足还望请教。会自动判断当前的域名与主域名,以下是形式:./
昨天在写用迅雷下载时,发现 ./a.jpg的文件转成迅雷不是网络地址,然后写了一个方法转换。目前处在PHP基础层次,有不足还望请教。
会自动判断当前的域名与主域名,以下是形式:
./a.jpg => http://about.w.com/a.jpg;
../a.jpg => http://www.w.com/a.jpg
/**
 * 相对路径转网络绝对路径
 * @param string $file
 * @return string
 */
function dirToHttpUrl($file) {

	//判断文件是否存在
	if (!file_exists($file)) {
		return false;
	}

	//域名
	$nowUrl = dirname('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);	//当前域名
	$tempUrl = explode('.', $_SERVER['HTTP_HOST']);
	$dirUrl = 'http://www.'.$tempUrl[1].'.'.$tempUrl[2].'/';					//主域名

	//文件路径的层次统计
	$tempFile = explode('../', $file);
	$tempNum = array_count_values($tempFile);

	if (array_key_exists('', $tempNum)) {
		$fileNum = $tempNum[''];
		$fileEnd = end($tempFile);
	} else {
		$fileNum = 0;
		$fileEnd = '/'.substr($tempFile[0], 2);
	}

	//域名层次统计
	$tempWeb = explode('/', $nowUrl);
	$tempWeb = array_slice($tempWeb, 3);
	$webNum = count($tempWeb);

	//文件对应的域名
	if ($fileNum > $webNum) {
		$nowUrl = $dirUrl;
	}

	//返回
	return $nowUrl.$fileEnd;

}

//dirToHttpUrl('./1.jpg');
精彩图集

赞助商链接