简体   繁体   中英

Download File Behind Login using cURL and PHP

I am trying to download a file behind a login using cURL and PHP. I am able to connect to the server and login properly using CURLOPT_POST; furthermore, my file downloads properly. However, the contents are corrupted and cannot be opened. On a side note, the file downloads onto the server, how would I use curl to download the file to a users local machine if this tool were ever on a public web server.

    // 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?";

Thanks for the help!

I figured it out. I just need curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); in order to prevent redirects from throwing me off.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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