Skip to content

Instantly share code, notes, and snippets.

@web-elite
Created January 14, 2024 13:44
Show Gist options
  • Select an option

  • Save web-elite/5f7da4e57c0e1021ffe662dd5e322eb6 to your computer and use it in GitHub Desktop.

Select an option

Save web-elite/5f7da4e57c0e1021ffe662dd5e322eb6 to your computer and use it in GitHub Desktop.
download file and save with pure php
function downloadLargeFile($fileUrl, $localFilePath)
{
// Create a stream context with a buffer size
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => [
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
],
],
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
],
]);
// Open the remote file using fopen with the created stream context
$remoteFile = fopen($fileUrl, 'rb', false, $context);
if (!$remoteFile) {
die('Failed to open remote file.');
}
// Open the local file for writing
$localFile = fopen($localFilePath, 'wb');
if (!$localFile) {
fclose($remoteFile);
die('Failed to open local file for writing.');
}
// Read and write the file in chunks
while (!feof($remoteFile)) {
// Read 1MB at a time
$chunk = fread($remoteFile, 1024 * 1024);
if ($chunk === false) {
fclose($remoteFile);
fclose($localFile);
die('Error reading from remote file.');
}
// Write the chunk to the local file
$writeResult = fwrite($localFile, $chunk);
if ($writeResult === false) {
fclose($remoteFile);
fclose($localFile);
die('Error writing to local file.');
}
}
// Close the file handles
fclose($remoteFile);
fclose($localFile);
echo 'File downloaded and saved successfully!';
}
$remoteFileURL = 'https://domain.com/file.zip';
$localFilePath = $_SERVER['DOCUMENT_ROOT'] . '/file.zip';
return downloadLargeFile($remoteFileURL, $localFilePath);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment