Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

CarlEOgden's avatar

File Download - Corrupt file

Hi

I've finally got my system downloading a file automatically, I had to re-write how I present the download option to the user - it's displayed in a VueJS component but allows the user to click the filename in a route so the code receives the location of the file and the filename.

My code now reads as follows:-

public function downloadFile($fileName, $location)
{

	$variable = \IDHelpers::getID();

	$ftp = Storage::createFtpDriver([
		'host'     => 'My FTP Server',
		'username' => $this->ftp_username,
		'password' => $this->ftp_password,
		'port'     => '21', // your ftp port
		'timeout'  => '30', // timeout setting
	]);

	// Set file path
	$path_parts = [
		config('tmp_folder'),
		$variable->ID,
	];

	$destination_path = implode('/', $path_parts);
	$destination = implode('/', [public_path(), $destination_path]);
	// Ensure agency destination exists
	\AppHelpers::makeDirectory($destination);
	// Ensure the property destination exists
	\AppHelpers::makeDirectory($destination.'/'.$location);
	// get the file from the ftp server
	$fileContents = ($ftp->get($location.'/'.$fileName));
	//store it in the tmp destination
	$localPath = $destination_path.'/'.$location;
	$localFile = $destination_path.'/'.$location.'/'.$fileName;
	$results = File::put($localFile, $fileContents);
	//
	// Initiate the download
	//
	$destination .= '/' . $location . '/' . $fileName;

	//$file = Storage::get($localFile);

	header('Content-Type: application/octet-stream');
	header("Content-Transfer-Encoding: Binary");
	header("Content-disposition: attachment; filename=\"" . $fileName . "\"");
	header("Content-Length: ".$results);
	readfile($localFile);
	return response()->file($localFile);
}

As I've had to rename stuff in the code for security, be assured the above code works as intended, I can get the file from the ftp location, put it in the tmp location on my server, the only bit that fails is the download, I suspect I've not got the header coded correctly as if I use FileZilla and download the file, it opens without issue, however, if I run the above and try to open the downloaded file, it fails.

Any idea on what setting I have that is incorrect?

Cheers Carl.

0 likes
2 replies
CarlEOgden's avatar

Hi

Further to this, I've now tested the routine downloading a PDF document, it works perfectly.

So there must be something being lost when loading a docx into memory, writing it to the local tmp storage and then when the readfile() routines downloads the file, it must be corrupted at that point.

Any ideas? Carl.

CarlEOgden's avatar
CarlEOgden
OP
Best Answer
Level 4

It was a corrupt docx, changed the code to do:-

readfile($localFile);
File::delete($localFile);
exit;

All sorted. Carl.

Please or to participate in this conversation.