Blog

It's a Wonderful Life

图片下载函数

2017-03-05 14:22 Posted in Learn with PHP

为了练习curl做的一个简单的图片下载函数:

<?php
function getImage($url, $filename = '', $path = '/var/www/html/downimgs/')
{
	$ext = pathinfo((parse_url($url))['path'], PATHINFO_EXTENSION);
	if ($ext !== 'jpg' && $ext !== 'jpeg' && $ext !== 'png')
	{
		echo "File invalid";
		return;
	}
	
	if (empty($filename))
	{
		$filename = time() . '.' . $ext;
	}
	else
	{
		$filename = $filename . '.' . $ext;
	}
	
	if ($path !== '/var/www/html/downimgs/')
	{
		if (! mkdir($path, 0777, true))
		{
			echo "Make path failed";
			return;
		}
	}
	
	$fullname = $path . '/' . $filename;
	$fullname = str_replace('//', '/', $fullname);
	
	$timeout = 5;
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	
	$img_content = curl_exec($ch);
	
	curl_close($ch);
	
	if ($fh = fopen($fullname, 'x'))
	{
		if (fwrite($fh, $img_content))
		{
			echo "Image download complete!";
			return;
			
		}
		else
		{
			echo "Couldn't download";
			//if due to poor internet connection or other reason that cause download failing, it'll still make a incomplete binary file in download directory which we should remove.
			unlink($fullname);
			return;
		}
	}
	else
	{
	    //if fopen() returns 'false' when tring to  open in 'x' mode, that means that file is already exists.
		echo "File exists";
		return;
	}
}