繁体   English   中英

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

[英]PHP CURL Login and Download file code not working

我正在尝试登录网站并下载一个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);

请尝试这个

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);

尝试在您的fopen函数中添加'w+'

将会 ..

$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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM