diff --git a/src/Curl/Curl.php b/src/Curl/Curl.php index 3ab770d..5156ec1 100644 --- a/src/Curl/Curl.php +++ b/src/Curl/Curl.php @@ -182,6 +182,16 @@ class Curl return $this->exec(); } + public function download($url, $filename) + { + $fh = fopen($filename, 'wb'); + $this->setOpt(CURLOPT_FILE, $fh); + $this->get($url); + fclose($fh); + $this->setOpt(CURLOPT_FILE, STDOUT); + return ! $this->error; + } + public function setBasicAuthentication($username, $password = '') { $this->setOpt(CURLOPT_HTTPAUTH, CURLAUTH_BASIC); diff --git a/tests/PHPCurlClass/PHPCurlClassTest.php b/tests/PHPCurlClass/PHPCurlClassTest.php index d32795e..e504013 100644 --- a/tests/PHPCurlClass/PHPCurlClassTest.php +++ b/tests/PHPCurlClass/PHPCurlClassTest.php @@ -330,6 +330,27 @@ class CurlTest extends PHPUnit_Framework_TestCase $this->assertEquals('OPTIONS', $test->curl->response_headers['X-REQUEST-METHOD']); } + public function testDownload() + { + $save_to_path = tempnam('/tmp', 'php-curl-class.'); + $file_path = Helper\get_png(); + + $test = new Test(); + $test->curl->setHeader('X-DEBUG-TEST', 'download_response'); + $this->assertTrue($test->curl->download(Test::TEST_URL, $save_to_path)); + $this->assertEquals(filesize($file_path), filesize($save_to_path)); + $this->assertEquals(md5_file($file_path), md5_file($save_to_path)); + $this->assertEquals(md5_file($file_path), $test->curl->response_headers['ETag']); + + $test->curl->setHeader('X-DEBUG-TEST', 'get'); + $test->curl->get(Test::TEST_URL); + + unlink($file_path); + unlink($save_to_path); + $this->assertFalse(file_exists($file_path)); + $this->assertFalse(file_exists($save_to_path)); + } + public function testBasicHttpAuth401Unauthorized() { $test = new Test(); diff --git a/tests/PHPCurlClass/server.php b/tests/PHPCurlClass/server.php index 8e78995..b8994a2 100644 --- a/tests/PHPCurlClass/server.php +++ b/tests/PHPCurlClass/server.php @@ -1,4 +1,8 @@ appendChild($channel); echo $doc->saveXML(); exit; +} elseif ($test === 'download_response') { + $png = Helper\create_png(); + header('Content-Type: image/png'); + header('Content-Disposition: attachment; filename="image.png"'); + header('Content-Length: ' . strlen($png)); + header('ETag: ' . md5($png)); + echo $png; + exit; } elseif ($test === 'error_message') { if (function_exists('http_response_code')) { http_response_code(401);