<?php // 初始化 $album = "album"; if (!is_dir($album)) { // 检测文件夹是否存在 mkdir($album); // 如果不存在则创建 } // 处理上传文件 if (isset($_POST["action"]) && $_POST["action"] == "upload") { // 检测上传请求 if (isset($_FILES["file"]["tmp_name"]) && $_FILES["file"]["error"] === 0) { // 检测文件上传成功 // 定义文件存放路径 $filename = $_FILES["file"]["name"]; $targetPath = $album . "/" . $filename; // 安全检查:只允许特定文件类型 $allowedTypes = array("jpg", "jpeg", "png", "gif"); $fileType = pathinfo($filename, PATHINFO_EXTENSION); if (in_array(strtolower($fileType), $allowedTypes)) { // 使用move_uploaded_file()移动临时文件 if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetPath)) { echo "上传文件成功!"; } else { echo "上传文件失败!"; } } else { echo "不允许的文件类型!"; } } else { echo "上传过程出错!"; } } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>相册</title> <style> body { margin:0; padding:0; background-color:#EFEFEF; font-size:12px; } ul { margin:0; padding:0; list-style:none; } a { color:#333; text-decoration:none; } a:hover { color:#999; } .album_out { width:98%; margin:10px; } .album_out img { margin:4px; border:1px solid #ccc; } .album_out li { float:left; width:180px; text-align:center; margin:5px; } </style> </head> <body> <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1"> <label>上传图像 <input type="file" name="file" /> </label> <label> <input type="submit" name="Submit" value="提交" /> <input type="hidden" name="action" value="upload" /> </label> </form> <hr size="1" /> <div class="album_out"> <ul> <?php $dh = dir($album); echo "相册目录: " . $dh->path . "<br>"; while (($file = $dh->read()) !== false) { if ($file != "." && $file != "..") { $filePath = $album . "/" . $file; // 安全检查:只显示图片文件 $fileType = pathinfo($filePath, PATHINFO_EXTENSION); if (in_array(strtolower($fileType), $allowedTypes)) { echo '<li><a href="' . $filePath . '" target="_blank"> <img src="' . $filePath . '" width="160" height="120" border="0" /> <br>' . htmlspecialchars($file) . '</a> </li>'; } } } $dh->close(); ?> </ul> </div> </body> </html>