简体   繁体   中英

Download csv file from url and save on server with username password

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'));

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

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