php利用curl保存图片

做验证码识别的时候需要先把图片保存起来,写了一个保存图片的函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @author mohuishou<1@lailin.xyz>
* @param string $url 获取图片的网址
* @param string $fileName 保存的地址以及文件名
*/
function getImg($url, $fileName)
{
$ch = curl_init();
$fp = fopen($fileName, 'w+');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_FILE,$fp);
curl_exec($ch);
curl_close($ch);
fclose($fp);
}

使用的时候发现,需要保存验证码的cookies,留作验证,必要的时候还需要加上header

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @author mohuishou<1@lailin.xyz>
* @param string $url
* @param string $fileName
*/
function getCode($url = 'http://www.169ol.com/Mall/Code/getCode', $fileName = './img/code.png')
{

$this->_code_cookie = dirname(__FILE__)."/pic.cookie";
$ch = curl_init();
$fp = fopen($fileName, 'w+');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_FILE,$fp);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->_code_cookie);

curl_exec($ch);
curl_close($ch);
fclose($fp);
}