php实现图片
图片上传功能实现
在PHP中实现图片上传功能需要处理表单提交、文件验证和存储等步骤。以下是一个完整的实现方法:
创建HTML表单用于上传图片
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*">
<input type="submit" value="上传图片">
</form>
处理上传的PHP脚本
创建upload.php文件处理上传逻辑

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
// 检查是否为真实图片
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($check === false) {
$uploadOk = 0;
}
// 检查文件是否已存在
if (file_exists($targetFile)) {
$uploadOk = 0;
}
// 限制文件大小(例如5MB)
if ($_FILES["image"]["size"] > 5000000) {
$uploadOk = 0;
}
// 允许特定文件格式
$allowedTypes = ["jpg", "png", "jpeg", "gif"];
if (!in_array($imageFileType, $allowedTypes)) {
$uploadOk = 0;
}
// 检查上传状态并移动文件
if ($uploadOk && move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) {
echo "文件上传成功";
} else {
echo "文件上传失败";
}
}
?>
图片显示功能
上传后显示图片的代码示例
<?php
$imageDir = "uploads/";
$images = glob($imageDir . "*.{jpg,jpeg,png,gif}", GLOB_BRACE);
foreach ($images as $image) {
echo '<img src="' . $image . '" style="max-width:300px; margin:10px;">';
}
?>
安全注意事项
确保上传目录有正确权限

// 建议设置上传目录权限为755
chmod("uploads/", 0755);
防止文件名注入攻击
$fileName = preg_replace("/[^a-zA-Z0-9\.]/", "", $_FILES["image"]["name"]);
使用随机文件名增加安全性
$newFileName = uniqid() . '.' . $imageFileType;
$targetFile = $targetDir . $newFileName;
图片处理扩展
使用GD库调整图片大小
function resizeImage($file, $maxWidth, $maxHeight) {
list($width, $height) = getimagesize($file);
$ratio = $width / $height;
if ($width > $maxWidth || $height > $maxHeight) {
if ($maxWidth / $maxHeight > $ratio) {
$newWidth = $maxHeight * $ratio;
$newHeight = $maxHeight;
} else {
$newWidth = $maxWidth;
$newHeight = $maxWidth / $ratio;
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($dst, $file);
}
}
以上代码提供了从上传到显示图片的完整流程,包含了基本的安全检查和图片处理功能。根据实际需求可以进一步扩展和完善这些功能。






