0

I want to download a csv file from a url and save that on my server. But the URL requires a username/password.

And I also want to include a timeout, so that it will not try to download it longer than 30 seconds.

I currently tried this, but that is missing the username / password.

How can I achive this?

file_put_contents("file.csv", fopen("http://url.com/path/to/file.csv", 'r'));
JGeer
  • 1,768
  • 1
  • 31
  • 75

1 Answers1

0

You need download file with curl

error_reporting(E_ALL);
ini_set('display_errors', 1);
$username = "user";
$password = "pass";
$url = "http://url/path/file.csv";
$fileout =  '/yourpath/filecurl.csv';
$fp = fopen ($fileout , 'w+');
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$output = curl_exec($ch);
curl_exec($ch); 
curl_close($ch);
fclose($fp);

Then read the file in a normal way with the method you like, this is basically the idea

  • Thanks! I tried that, but that does not seem to work. It does not download/save any file. – JGeer Mar 20 '17 at 13:58
  • This found, change quotes at this `"$username:$password"` – Guillermo Andres Fuentes Moral Mar 20 '17 at 14:17
  • Thanks, but I get multiple errors: `failed to open stream: Permission denied` and `curl_setopt(): supplied argument is not a valid File-Handle resource` and `fclose() expects parameter 1 to be resource, boolean given` – JGeer Mar 20 '17 at 14:38
  • You Tried first change permision dir fileout `$fileout = '/yourpath/filecurl.csv';` chmod 755? or 777, second change time CURLOPT_TIMEOUT, tried this! – Guillermo Andres Fuentes Moral Mar 20 '17 at 14:46
  • Thanks, yes I tried setting the permissions right. I increased the time in CURLOPT_TIMEOUT but I still get the same error's. Do I first need to create the file `/yourpath/filecurl.csv` mannualy or will it be created by curl? – JGeer Mar 21 '17 at 10:54
  • not `/yourpath/filecurl.csv` create automatic by script, but need permission 777 in this path `/yourpath` – Guillermo Andres Fuentes Moral Mar 21 '17 at 15:28