获取远程图片保存至本地函数

<?php
set_time_limit (0);  //避免页面超时
/**
 * 获取远程图片保存到本地function
 * by hkshadow
 * date:2011-06-30 AM:10:30
 * edit:2011-06-30 PM:16:24
 * Enter description here ...
 * @param unknown_type $url
 * @param unknown_type $filename
 */
function SavePicLocal($url, $filename = "") {
	if ($url == "") :
		return false;
	endif;
	
	$files = "../../wedding/uploads/vidiopic";
	$tofile = date ( "Y" );
	$tofilem = date ( "m" );
	$tofiled = date ( "d" );
	
	$dir_name .= $files . "/" . $tofile."/";
	if (! file_exists ( $dir_name )) //判断文件夹是否存在
	{
		mkdir ( $dir_name, 0777 );
		@chmod ( $dir_name, 0777 );
	}
	
	$dir_name .= $tofilem."/";

	if (! file_exists ( $dir_name )) //判断文件夹是否存在
	{
		mkdir ( $dir_name, 0777 );
		@chmod ( $dir_name, 0777 );
	}
	$dir_name .= $tofiled;

	if (! file_exists ( $dir_name )) //判断文件夹是否存在
	{
		mkdir ( $dir_name, 0777 );
		@chmod ( $dir_name, 0777 );
	}
	
	
	if ($filename == "") {
		$ext = strrchr ( $url, "." );
		//   if($ext!=".gif" && $ext!=".jpg"):return false;endif;
		if ($ext != ".gif" && $ext != ".jpg") {
			$filename = $dir_name . "/" . date ( "dMYHis" ) . ".png";
		} else {
			$filename = $dir_name . "/" . date ( "dMYHis" ) . $ext;
		}
	}
	
	ob_start ();
	readfile ( $url );
	$img = ob_get_contents ();
	ob_end_clean ();
	$size = strlen ( $img ); //文件大小
	$fp2 = @fopen ( $filename, "a" );
	fwrite ( $fp2, $img );
	fclose ( $fp2 );
	
	return $filename;
}
?>

Leave a Reply

(will not be published)