メニュー

小金井にあるWEB制作会社の備忘録

MEMORANDUM

PHPを使用して入力フォームで選択したファイルを圧縮ダウンロードする

ホワイトペーパーのダウンロードを実装した際に、数が増え、単体で何回もフォームの入力操作を行ってもらうのも不便なので、複数のファイルを同時にダウンロードできるように実装した方法をメモ。

HTML

<form action="download.php" method="post">
<input type="hidden" name="download__token" value="xxxxxxxxxx">
<dl>
<dt>メールアドレス</dt>
<dd><input type="text" name="email" placeholder="例)mail@example.com"></dd>
<dt>希望ファイル</dt>
<dd><?php FormCheckboxary($dlfiles, 'doc', $dt['doc'], 'label'); ?></dd>
</dl>
<div class="btnSubmit"><input type="submit" name="download" value="選択ファイルを圧縮してダウンロード"></div>
</form>

download.php(PHP)

$dlfiles = array(
	1=> array('label'=> '○○○○', 'name'=>'○○○○.pdf'),
	array('label'=> '△△△△', 'name'=>'△△△△.xlsx'),
	array('label'=> '□□□□', 'name'=>'□□□□.xlsx')
);

if(!empty($_POST['download'])){
	
	// フォームの取得
	foreach($_POST as $key => $value){
		if(!is_array($_POST[$key])){
			$dt[$key] = $value;
		}else{
			foreach($_POST[$key] as $innerkey => $value){
				$dt[$key][$innerkey] = $value;
			}
		}
	}

	// エラー処理省略
	
	// 圧縮対象のフォルダ
	$sourceDir = '../dlfiles/'; // ファイルが保存されているフォルダ
	$zipFileName = 'compressed_documents.zip'; // ZIPファイル名
	$zipFilePath = __DIR__ .'/'.$zipFileName;

	// ZIPオブジェクトの作成
	$zip = new ZipArchive();
	if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
		die('ZIPファイルを作成できませんでした。');
	}

	// 指定フォルダ内の対象ファイルを取得
	foreach($dt['doc'] as $val){
		$filePath = $sourceDir.$dlfiles[$val]['name'];
		if(is_file($filePath)) {
			$zip->addFile($filePath, basename($filePath));
		}
	}
	$zip->close();

	// ZIPをダウンロードさせる
	header('Content-Type: application/zip');
	header('Content-Disposition: attachment; filename="'.$zipFileName.'"');
	header('Content-Length: '.filesize($zipFilePath));
	readfile($zipFilePath);

	// 一時ZIPファイルを削除
	unlink($zipFilePath);

	exit;
}

function FormCheckboxary($array, $name, $no, $id){
	echo('<ul>');
	foreach($array as $key => $value){
		$str=explode("<>", $no);
		if(in_array($key, $str)){
			echo('<li><input type="checkbox" name="'.$name.'[]" value="'.$key.'" checked="checked" id="checkbox'.$name.$key.'"><label for="checkbox'.$name.$key.'">'.$value[$id].'</label></li>');
		}else{
			echo('<li><input type="checkbox" name="'.$name.'[]" value="'.$key.'" id="checkbox'.$name.$key.'"><label for="checkbox'.$name.$key.'">'.$value[$id].'</label></li>');
		}
	}
	echo("</ul>");
	return;
}

対象ファイルのリストを連想配列で作成し、チェックボックスで選択したもののみをZIP形式でダウンロードできるようにしています。

RANKING

人気記事

同一カテゴリーの記事