使用cURL和PHP下载登录后面的文件

时间:2015-07-29 20:01:23

标签: php curl

我正在尝试使用cURL和PHP下载登录后的文件。我可以使用CURLOPT_POST连接到服务器并正确登录;此外,我的文件正确下载。但是,内容已损坏,无法打开。在旁注中,文件下载到服务器上,如果此工具曾在公共Web服务器上,我将如何使用curl将文件下载到用户本地计算机。

    // POST data from JSTOR Tool
    $username = $_POST['username'];
    $password = $_POST['password'];
    $start = $_POST['start'];
    $end = $_POST['end'];
    $loginUrl="https://www.jstor.org/action/doLogin"; 

    print "Hello $username, your articles are downloading.";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.jstor.org/action/doLogin');
    curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "login=".$username."&password=".$password);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  
    curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp'); 
    $answer = curl_exec($ch);
    if (curl_error($ch)) {
        echo curl_error($ch);
    }

    //another request to download the article, but preserves the session

    curl_setopt($ch, CURLOPT_URL, 'http://www.jstor.org/stable/pdf/1.pdf');
    curl_setopt($ch, CURLOPT_POST, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSLVERSION,3);
    $data = curl_exec ($ch);
    print_r($data);
    $error = curl_error($ch); 
    curl_close ($ch);

    $destination = "./files/test.pdf";
    $file = fopen($destination, "w");
    fputs($file, $data);
    fclose($file);

    print " Did it work?";

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我明白了。我只需要curl_setopt($ ch,CURLOPT_FOLLOWLOCATION,TRUE);为了防止重定向让我失望。