PHP上传图片并显示图片涉及以下几个基础概念:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
} else {
echo "File is not an image.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Display Image</title>
</head>
<body>
<?php
$image_path = "uploads/your_image.jpg"; // 替换为实际图片路径
if (file_exists($image_path)) {
echo '<img src="' . $image_path . '" alt="Uploaded Image">';
} else {
echo "Image not found.";
}
?>
</body>
</html>
upload_max_filesize
和post_max_size
设置,确保上传目录有写权限。通过以上步骤和代码示例,你可以实现PHP上传图片并显示图片的功能。如果遇到具体问题,可以根据错误信息进行排查和解决。
领取专属 10元无门槛券
手把手带您无忧上云