Altimus Prime
Altimus Prime

Reputation: 2327

How to retrieve attachment with http response header using PHP cURL library

I'm trying to retrieve the raw attachment of an http request made using the php cURL library. Right now I get the html response but not the attachment.

There's a very similar question here that says use cURL option -j. I can't find the equivalent set_opt in the php cURL library.

When I make a request in the browser the desired attachment is referred to in the header information and the browser knows to download it automatically. In my script I just need the raw data of the attachment loaded into a variable.

How do I load the attachment data into a variable in php?

Header response from remote server:

Cache-Control:must-revalidate, post-check=0, pre-check=0
Content-Disposition:attachment; filename=exel_file.xls
Content-Length:65
Content-Transfer-Encoding:binary
Content-Type:application/download
Date:Thu, 30 Jun 2016 15:12:05 GMT
Expires:Mon, 26 Jul 1997 05:00:00 GMT
Last-Modified:Thu, 30 Jun 2016 16:33:14 GMT
Pragma:public
Server:Microsoft-IIS/7.5
X-Powered-By:PHP/5.2.17

My php cURL request:

$url = "https://subdomain.example.com?parameter=1";
$post = "post1=false&".
        "post2=&".
        "post3=false&".
        "post4=&".
        "post5=&".
        "post6=1243123421";

$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookieFile); 
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookieFile); 
curl_setopt($ch, CURLOPT_USERAGENT,  $userAgent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER,    1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$html = curl_exec($ch);

I've already tried accessing exel_file.xls directly at https://subdomain.example.com/exel_file.xls and to no avail.

UPDATE: I did manage to directly reach the file eventually when I found it in Chrome developer tools. I filtered the network responses to "doc" and found the request tied to the attachment. The file was located at https://example.com/exel_file.xls instead of https://subdomain.example.com/exel_file.xls.

Upvotes: 1

Views: 2645

Answers (1)

mujuonly
mujuonly

Reputation: 11861

Set CURLOPT_BINARYTRANSFER to TRUE and set the content type.

<?php

$url = "http://slackbuilds.org/slackbuilds/13.37/multimedia/umplayer.tar.gz";
$opts = array(
  CURLOPT_URL =>$url,
  CURLINFO_CONTENT_TYPE => "text/xml",
  CURLOPT_BINARYTRANSFER => TRUE,
  CURLOPT_RETURNTRANSFER => TRUE
);

$ch = curl_init();
curl_setopt_array($ch, $opts);
$data = curl_exec($ch);
$info = curl_getinfo($ch); 
curl_close($ch);

header("Content-Type: application/x-gzip"); 
header("Content-disposition: attachment; filename=zipfile.tar.gz");

echo $data;
?>

Does this help

Upvotes: 1

Related Questions