PHP CURL登录和下载文件代码不起作用

时间:2016-01-30 11:31:31

标签: php csv curl cookies session-cookies

我正在尝试登录网站并下载csv文件,登录似乎有效,但csv文件没有下载,当我手动执行这些操作时我可以毫无问题地下载该文件。它没有给出任何错误消息,var_dump输出显示“true”

任何人都可以帮我骗狐狸,谢谢

define( 'LOGINURL', 'http://www.highlite.nl/user/login' );
define( 'LOGINFIELDS', 'Login=xxxxxx&Password=xxxx&LoginButton=LoginButton' );
define( 'DWNLDURL', 'http://www.highlite.nl/silver.download/download/products_v2_0.csv' );
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
$fp = fopen("/tmp/import.csv", "w");                  

/* STEP 2. visit the login page to authenticate and set the cookie properly */
$ch = curl_init( LOGINURL );
curl_setopt( $ch, CURLOPT_COOKIESESSION, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, LOGINFIELDS );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

$output = curl_exec( $ch );

/* STEP 3. request download */
$ch = curl_init();
curl_setopt( $ch, CURLOPT_COOKIEFILE, $ckfile );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_URL,DWNLDURL);
curl_setopt($ch, CURLOPT_FILE, $fp);
//curl_setopt($ch, CURLOPT_URL, $ch);
$result = curl_exec( $ch ); 

var_dump($result);

2 个答案:

答案 0 :(得分:1)

请尝试使用此

define( 'LOGINURL', 'http://www.highlite.nl/user/login' );
define( 'LOGINFIELDS', 'Login=xxxxxx&Password=xxxx&LoginButton=LoginButton' );
define( 'DWNLDURL', 'http://www.highlite.nl/silver.download/download/products_v2_0.csv' );
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
$fp = fopen("/tmp/import.csv", "w+"); // Changed w to w+                  

/* STEP 2. visit the login page to authenticate and set the cookie properly */
$ch = curl_init( LOGINURL );
curl_setopt( $ch, CURLOPT_COOKIESESSION, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, LOGINFIELDS );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

$output = curl_exec( $ch );

/* STEP 3. request download */ /*Updated code*/
$ch = curl_init(DWNLDURL);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_ENCODING, "");
$result = curl_exec( $ch ); 
curl_close($ch);
fclose($fp);
var_dump($result);

答案 1 :(得分:1)

尝试将'w+'添加到您的fopen函数

将是..

$fp = fopen("/tmp/import.csv", "w+");   

成功时,fopen函数将返回文件指针资源。请注意,我们传入“w +”作为第二个参数,因为“w +”告诉PHP我们要打开文件进行读写。

在我们成功设置文件指针后,我们可以通过CURLOPT_FILE选项将其交给cURL,就像你已经在做的那样。

//Pass our file handle to cURL.
curl_setopt($ch, CURLOPT_FILE, $fp);