Home  >  Article  >  Backend Development  >  An example of PHP image collection function

An example of PHP image collection function

PHP中文网
PHP中文网Original
2016-07-25 08:55:381209browse

An example of PHP image collection function

<p><?
/**
* 采集图片函数
* func: getimg
* params: $url 网址 $filepath 图片文件的路径
* by bbs.it-home.org
*/
function getimg($url, $filepath) { </p>
<p> if ($url == &#39;&#39;) {
return false;
}
$ext = strrchr($url, &#39;.&#39;); </p>
<p> if ($ext != &#39;.gif&#39; && $ext != &#39;.jpg&#39;) {
return false;
} </p>
<p> //判断路经是否存在
!is_dir($filepath)?mkdir($filepath):null; </p>
<p> //获得随机的图片名,并加上后辍名
$filetime = time();
$filename = date("YmdHis",$filetime).rand(100,999).&#39;.&#39;.substr($url,-3,3); </p>
<p> //读取图片
$img = fetch_urlpage_contents($url);
//指定打开的文件
$fp = @ fopen($filepath.&#39;/&#39;.$filename, &#39;a&#39;);
//写入图片到指定的文本
fwrite($fp, $img);
fclose($fp);
return &#39;/&#39;.$filepath.&#39;/&#39;.$filename;
}
function fetch_urlpage_contents($url){
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_TIMEOUT, 1000);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
}
echo getimg(") //图片地址 //保存路径 //返回保存后路径
?></p>

The above is the content of an example of PHP image collection function. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn