PHP文件上传-多个文件
我正在尝试使用以下 PHP 上传多个图像。上传的图像数量可以变化。
我似乎遇到的问题是图像编号 1 没有上传,但它的文件路径正在打印到屏幕上。
代码:-
if ($_FILES['pac_img_1']['name']>""){
echo("You have uploaded the following images:-<ul>");
for ($i=1; $i<=$imagesCount; $i++){
$target_path = "files/" . $companyName . "/images/";
$target_path = $target_path . basename( $_FILES['pac_img_' . $i]['name']);
if(move_uploaded_file($_FILES['pac_img_' . $i]['tmp_name'], $target_path)) {
echo "<li><a href='". $target_path . "'>". basename( $_FILES['pac_img_' . $i]['name']). "</a></li>";
} else{
echo "There was an error uploading an image";
}
};
echo("</ul>");
}else{
echo("None uploaded");
};
我根据以前使用过的一些代码改编了它,所以我怀疑我在这里犯了“小学生”错误。
如有帮助,将不胜感激。
编辑以添加 $imagesCount 通过 $_POST 请求从表单元素获取其值。当仅上传一张图像时,该值 = 0。
using the following PHP I am attempting to upload multiple images. The number of images upload can be varied.
The problem that I seem to have is that image number 1 isn't being uploaded however it's filepath is being printed to the screen.
The code:-
if ($_FILES['pac_img_1']['name']>""){
echo("You have uploaded the following images:-<ul>");
for ($i=1; $i<=$imagesCount; $i++){
$target_path = "files/" . $companyName . "/images/";
$target_path = $target_path . basename( $_FILES['pac_img_' . $i]['name']);
if(move_uploaded_file($_FILES['pac_img_' . $i]['tmp_name'], $target_path)) {
echo "<li><a href='". $target_path . "'>". basename( $_FILES['pac_img_' . $i]['name']). "</a></li>";
} else{
echo "There was an error uploading an image";
}
};
echo("</ul>");
}else{
echo("None uploaded");
};
I have adapted it from some code that I've used before so I suspect I am guilty of a "schoolboy" error here.
Help would be appreciated.
Edit to add that $imagesCount takes its value from a form element via a $_POST request. When only one image is uploaded that value = 0.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根本不是 php-dude,我会尝试更改
为
- 或者可能
取决于 $imagesCount 的设置方式。
Without being a php-dude at all, I'd try changing
to
-or maybe
depending on how $imagesCount is set.
实际上,它循环了几个 $_POST 项。他的 HTML 可能有类似这样的内容:
他正在尝试获取这些图像。
我会采取不同的做法。
HTML:(
请注意,您可以动态添加文件输入,而不必担心名称)
PHP:
最后但并非最不重要的一点:始终检查上传的文件是否符合其预期。 (http://www.acunetix.com/websitesecurity/upload-forms-threat。嗯)
Actually, it's looping through several $_POST itens. His HTML probably has something like:
and he is trying to get these images.
I would do this differently.
HTML:
(note that you can dynamically add file inputs without worrying about names)
PHP:
And last, but not least: ALWAYS check if uploaded files are what they suposed to be. (http://www.acunetix.com/websitesecurity/upload-forms-threat.htm)
您的 for 循环需要修改。数组索引从 0 开始。最后一个元素应该是数组长度 - 1;
您的 for 循环需要修改为以下代码示例。
Your for loop need to be modified. Array indexes starts from 0. And the last element should be Array length - 1;
Your for loop need to be modified as bellow code sample.