ファイルの表示件数が多くなってきたのでページング機能を追加しました。
<?php
$upload_dir = '/var/www/html/php/upload/';
if (array_key_exists('upfile', $_FILES)) {
$upload_file = $upload_dir . basename($_FILES['upfile']['name']);
move_uploaded_file($_FILES['upfile']['tmp_name'], $upload_file);
}
$page = $_REQUEST['page'];
$maxLine = 30;
if ($page == "" ) {
$page = 1;
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>PHPサンプル - ファイルのアップロード</title>
</head>
<body>
<?php
if (array_key_exists('delfile', $_POST)) {
$delete_file = $upload_dir . $_POST['delfile'];
if (unlink($delete_file)){
echo $_POST['delfile'] . "削除しました。";
} else {
echo $_POST['delfile'] . "削除が失敗しました。";
}
}
?>
<hr>
<form method="post" enctype="multipart/form-data">
<input type="file" name="upfile">
<button type="submit">送信</button>
</form>
<hr>
<?php
$search = $upload_dir . "*.*";
$i = 0;
$ii = -1;
foreach (glob($search) as $filename) {
$i += 1;
if ((int)($i/$maxLine) == ($page-1)) {
$ii = $i;
$filepath = pathinfo($filename);
echo "<div>";
echo $ii.".";
echo "<a href='./upload/".$filepath['basename']."' target='_blank'>".$filepath['filename']."</a>";
echo "<form style='display:inline' method='post'><input type='hidden' name='delfile' value='" . $filepath['basename'] . "'><button type='submit'>削除</button></form>";
echo "</div>";
}
}
echo "<hr><div>";
if ($page > 1) {
echo "<a href='./upload.php?page=".(1)."'>先頭</a> ";
echo "<a href='./upload.php?page=".($page-1)."'>前へ</a> ";
}
$pageLimit = $page + 5;
$pageMax = (int)($i / $maxLine) + 1;
if ($pageLimit > $pageMax){
$pageLimit = $pageMax;
}
for($idx = $page; $idx <= ($pageLimit); $idx += 1) {
$t = $idx;
if ($pageMax != $pageLimit and $idx == $pageLimit){
$t = "..";
}
echo "<a href='./upload.php?page=".($idx)."'>". $t ."</a> ";
}
if ($ii < $i) {
echo "<a href='./upload.php?page=".($page+1)."'>次へ</a> ";
echo "<a href='./upload.php?page=".($pageMax)."'>末尾</a> ";
}
echo "</div>";
?>
</body>
</html>
コメント