Warning: Use of undefined constant OPTION_FILES - assumed 'OPTION_FILES' (this will throw an Error in a future version of PHP) in /homepages/22/d257667558/htdocs/myblog/wordpress/wp-content/themes/magazeen/functions.php on line 429
用 curl 登录 然后 下载文件 « 咚咚和隆隆的blog
Check out the Latest Articles:

在工作中遇到需要登录一个网站然后从这个网站下载一些东西问题,经过一天的编写,查找和测试,做出以下代码用于实现.

$dir = “/home/tools/ctemp”;
$cookie_file_path = $dir.”/cookie.tmp”;

function get_connexion($cookie_file_path) {

$username = “xxxxx”;
$password = “xxxxx”;

$url = ‘https://xxxxxxxxx/xxxxxx/xxxxx’;
$postinfo = “login=”.$username.”&password=”.$password;

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 这个如果不设置,默认是检测ssl链接的,会报错

curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
//set the cookie the site has for certain features, this is optional
curl_setopt($ch, CURLOPT_COOKIE, “xxxxxxxxxx”);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, “POST”);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
curl_exec($ch);
curl_close($ch);

}

// 下载文件

function get_content($source, $cookie) {

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_HEADER, 1); // 将头文件的信息作为数据流输出。我在下载时候这个要是设置为负,下载就失败,没找到原因,但是这个应该可以根据情况自己设定
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //将获取的信息以字符串返回,而不是直接输出。根据情况自己设定
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 强制根据头文件中的location定向,不然有些网站会自动定向到其他网页,造成下载失败
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 这个如果不设置,默认是检测ssl链接的,会报错
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); //lire le cookie
$rs = curl_exec($ch); //récupéré les contenu
syslog(LOG_ERR, “curl get content ” . curl_error($ch));
curl_close($ch);
return $rs;

}

 



  1. It‘s quite in here! Why not leave a response?



0