$audioUrl = $audio["url"]; $filePath = "dl/" . md5($audioId) . ".mp3"; //caching mp3s, md5 for unique audioIds if (file_exists($filePath)) { if ($isStream) { stream($filePath, $fileName); } else { forceDownload($filePath, $fileName); } return; } else { if (downloadFile($audioUrl, $filePath)) { if ($isStream) { stream($filePath, $fileName); } else { forceDownload($filePath, $fileName); } } } //Functions /** * Download file with given name to given path * @param $url url to download * @param $path output filepath * @return true if success, else you know what */ function downloadFile($url, $path) { $fp = fopen($path, 'wb'); $ch = curl_init($url); curl_setopt($ch, CURLOPT_FILE, $fp);
header('Pragma: public'); header('Cache-Control: private', false); header('Content-Type:' . $mimeType); header('Content-Disposition: attachment; filename="' . basename($file) . '"'); header('Content-Transfer-Encoding: binary'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Content-Length: ' . filesize($file)); header('Connection: close'); readfile($file); exit; } else { return "File does not exist"; } } if (isset($_REQUEST['file']) && !empty($_REQUEST['file'])) { forceDownload($_REQUEST['file']); } ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Force download script in php</title> </head> <body> <h3>Force download script in php</h3> <form action="" method="post"> <input type="hidden" name="file" value="download/panda.jpg"> <button type="submit">Force Download</button> </form> </body>
} $audioGetUrl = "https://api.vk.com/method/audio.getById?audios=" . $audioId . "&access_token=" . $token; $response = file_get_contents($audioGetUrl); $json = json_decode($response, true); if (empty($json['response'])) { notFound(); } $audio = $json['response'][0]; $filename = makeSafe(transliterate($audio["artist"] . " - " . $audio["title"] . ".mp3")); $audioUrl = $audio["url"]; $fullpath = "dl/" . $filename; if (file_exists($fullpath)) { forceDownload($fullpath, $filename); } else { if (downloadFile($audioUrl, $fullpath)) { forceDownload($fullpath, $filename); } } function notFound() { header('HTTP/1.0 404 Not Found'); readfile("/home/alashov/www/.config/404.html"); exit; } function makeSafe($file) { $file = rtrim($file, '.'); $regex = array('#(\\.){2,}#', '#[^A-Za-z0-9\\.\\_\\- ]#', '#^\\.#'); return trim(preg_replace($regex, '', $file)); } function transliterate($textcyr = null, $textlat = null)