php 如何将简单的图像上传添加到表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4422210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:02:02  来源:igfitidea点击:

How to add simple image upload to a form?

phpimageformsfile-uploadasyncfileupload

提问by ninja208

I have a html form. I want to add a simple image upload feature to it and it will be send the image to a php page called "next.php". Any suggestions on how to do it?

我有一个 html 表单。我想给它添加一个简单的图片上传功能,它会将图片发送到一个名为“next.php”的 php 页面。关于如何做到这一点的任何建议?

回答by ninja208

Create an HTML form like the following:

创建一个 HTML 表单,如下所示:

<html>
<body>
<form action="next.php" method="post" enctype="multipart/form-data">
<label for="image">Image:</label>
<input type="image" name="image" id="image" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Your "next.php" file could handle the image similar to this:

您的“next.php”文件可以处理与此类似的图像:

<?php

if ($_FILES["file"]["error"] > 0)
    echo "Error: " . $_FILES["image"]["error"] . "<br />";
else
{
    echo "Upload: " . $_FILES["image"]["name"] . "<br />";
    echo "Type: " . $_FILES["image"]["type"] . "<br />";
    echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb<br />";
    echo "Stored in: " . $_FILES["image"]["tmp_name"];
}

At this point, you can make it more secure by checking the type and ensuring it's only jpg, gif, png, or of the sort. I would recommend copying the image into 2 or 3 sizes (thumb, medium, original), and deleting it from the temporary directory. You could use ImageMagickto resize the images and then use the filesystemfunctions to move around and delete temporary uploads.

在这一点上,您可以通过检查类型并确保它只是 jpg、gif、png 或类似的类型来使其更安全。我建议将图像复制为 2 或 3 种尺寸(拇指、中等、原始),并将其从临时目录中删除。您可以使用ImageMagick调整图像大小,然后使用文件系统功能移动并删除临时上传。

回答by David says reinstate Monica

I'm not aware of any means to interact with a file inputon the client-side, so you'll need to verify/validate the uploaded file server-side (within the 'next.php' script), but this should be enough:

我不知道input在客户端与文件交互的任何方法,因此您需要验证/验证上传的文件服务器端(在“next.php”脚本中),但这应该足够了:

<form action="path/to/next.php" method="post" enctype="multipart/form-data">
    <fieldset>
        <input type="file" name="picture" id="picture" />
    </fieldset>
</form>