I've been using this function to download a repository from bitbucket:
function download($url, $destination) {
try {
$fp = fopen($destination, "w");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, USERNAME . ":" . PASSWORD);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$resp = curl_exec($ch);
if(curl_errno($ch)){
throw new Exception(curl_error($ch), 500);
}
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status_code != 200) {
throw new Exception("Response with Status Code [" . $status_code . "].", 500);
}
}
catch(Exception $ex) {
if ($ch != null) curl_close($ch);
if ($fp != null) fclose($fp);
throw new Exception('Unable to properly download file from url=[' + $url + '] to path [' + $destination + '].', 500, $ex);
}
if ($ch != null) curl_close($ch);
if ($fp != null) fclose($fp);
}