简体   繁体   中英

Download PDF from remote server using PHP

I'm trying to download a .PDF using PHP. I have used this script a few times to download jpegs but for some reason the PDFs of giving me trouble.

I could manually download these PDFs one by one but it would take ages.

    $csv = array_map('str_getcsv', file('upc.csv'));
    $count = count($csv) - 1;

    $i = '0';
    while($i <= 2){
    $data_upc = $csv[$i][0];

    $curl = 'site.com'.$data_upc.'#colors';
    $ch = curl_init($curl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36');
    curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);    // No certificate
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);     // Follow redirects
    curl_setopt($ch, CURLOPT_MAXREDIRS, 4);             // Limit redirections to four
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    preg_match('/<a href="\/assets\/hlr-system(.*?)</',$response,$match);

    $pdf_url = $match[1];

    $pdf_url = 'beginning-url'.str_replace('" class="pdf">Spec Sheet','',$pdf_url);

    $pdf = 'brand/'.$data_upc.'.pdf';
    file_put_contents($pdf, fopen($pdf_url));


    echo 'testing: '.$pdf_url;
    echo '<br />';

    $i++;

    }

Take this function, loop over it and feed the PDF url.

  • $url is the full PDF URL
  • $copyPath is the full path of the new file

The function:

function downloadFile($url, $copyPath) {
    $pdf = file_get_contents($url);
    file_put_contents ($copyPath, $pdf);
}

Edit

For example how to loop over the function:

$arr[] = 'http://link1';
$arr[] = 'http://link2';
$arr[] = 'http://link3';

$num = 1;
foreach ($arr as $link) {
    downloadFile($url, "file{$num}.pdf");
    $num++;
}

function downloadFile($url, $copyPath) {
    $pdf = file_get_contents($url);
    file_put_contents ($copyPath, $pdf);
}

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