Harshdeep
Harshdeep

Reputation: 5814

How to download a file over https using php

I need to download an xml file using PHP. I am able to read the contents of file by setting following options when making a curl call to it.

curl_setopt ($http, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ($http, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($http,CURLOPT_USERAGENT,'XYZ');

As evident from above snippet I need to make VERIFYHOST as false and also need to set an explicit USERAGENT when making a call to read the file because the file is not publicly accessible and only a specific application can make call to read it (Web-Security techniques and stuff)

But how do I download the same file, I have tried readfile, fopen/fpassthru, file_get_contents but nothing seems to be working. Readfile gives the error failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden

Is there a way to provide curl like options with fopen or readfile, I think that may be the easiest approach to solve this. I could not find much help in PHP documentation.

Please help.

Upvotes: 3

Views: 3551

Answers (1)

Mike B
Mike B

Reputation: 32145

You need to attach your special user-agent to the stream context.

From http://www.php.net/manual/en/wrappers.http.php

Allows read-only access to files/resources via HTTP 1.0, using the HTTP GET method. A Host: header is sent with the request to handle name-based virtual hosts. If you have configured a user_agent string using your php.ini file or the stream context, it will also be included in the request.

Example #2 from the link above:

<?php
ini_set('user_agent', "PHP\r\nX-MyCustomHeader: Foo");

$fp = fopen('http://www.example.com/index.php', 'r');
?>

Upvotes: 3

Related Questions