1

I need to download a file from a webDAV site using PHP. I have tried the code below using cURL but I get a "400 Bad Request" error.

Can someone help me with what I am doing wrong?

$fp = fopen("c:/downloadtest.text", "w");

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

$result = curl_exec ($ch);

curl_close ($ch);

fclose($fp);
Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
user3101337
  • 364
  • 8
  • 24
  • The path is in the $URL variable, I just can;t really share it on the web. I was using fopen to eventually save the result. – user3101337 Oct 26 '17 at 20:56
  • That's not how you write to a file. https://stackoverflow.com/questions/7967531/php-curl-writing-to-file - You need to get the response from curl and use `fwrite` to actually write it (and you should use `CURLOPT_WRITEFUNCTION` to make it more memory efficient). – M. Eriksson Oct 26 '17 at 20:57
  • I adjusted the code below to match the link you provided, I get an empty file.I'm not sure how to post the new code, do I edit my original post? – user3101337 Oct 26 '17 at 21:17
  • Does this answer your question? [PHP cURL, writing to file](https://stackoverflow.com/questions/7967531/php-curl-writing-to-file) – Richard Chambers Jan 03 '21 at 23:32

1 Answers1

1

I finally got it working, I was not sure how to make the CURLOPT_WRITEFUNCTION option work:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

$output = curl_exec($ch);

$fp = fopen("c:/downloadtest.text", "w");
fwrite($fp, $output);
fclose($fp);

curl_close($ch);
user3101337
  • 364
  • 8
  • 24
  • See this answer [PHP cURL, writing to file](https://stackoverflow.com/questions/7967531/php-curl-writing-to-file) especially this posted answer, https://stackoverflow.com/a/62617724/1466970 , which quotes that "CURLOPT_FILE depends on CURLOPT_RETURNTRANSFER being set". And see posted answer https://stackoverflow.com/a/28607419/1466970 which shows how to check what `curl` is doing with the `-v` option to turn on verbose mode documenting what `curl` is doing and responses. – Richard Chambers Jan 03 '21 at 23:47