troubleshooting Question

Download a file to server from a url that require authentication

Avatar of lgduong
lgduongFlag for United States of America asked on
PHPApache Web Server
8 Comments1 Solution2843 ViewsLast Modified:
I am given a url when I am to enter my user credential and a CSV file can be saved or opened.
This work and I am able to see the content of the CSV file.
Now, I want to create a PHP script on my web server in which I can have the file be downloaded to a location I specify.

$username = 'userinfo';
$password = 'userpassword';

$remote_url = "";

$context = stream_context_create(array(
    'http' => array(
        'header'  => "Authorization: Basic " . base64_encode("$username:$password")

$fileName = file_get_contents($remote_url, false, $context);

$filePath = "csv/files/".$fileName;

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=\"$filePath \""); 
header("Content-type: text/csv");
header("Content-Transfer-Encoding: binary");

What am I doing wrong?  Can someone please help?


Edward Millen

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 8 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 8 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros