[英]PHP file upload - multiple files
使用以下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。
完全不用php-dude,我会尝试更改
for ($i=1; $i<=$imagesCount; $i++){
至
for ($i=0; $i<=$imagesCount; $i++){
-或者可能
for ($i=0; $i < $imagesCount; $i++){
取决于$ imagesCount的设置方式。
您的for循环需要修改。 数组索引从0开始。最后一个元素应为数组长度-1;
您的for循环需要修改为以下代码示例。
if ($_FILES['pac_img_1']['name']>""){
echo("You have uploaded the following images:-<ul>");
for ($i=0; $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");
};
您的for循环需要修改。 数组索引从0开始。最后一个元素应为数组长度-1; 您的for循环需要修改为以下代码示例。
实际上,它遍历了多个$ _POST itens。 他的HTML可能类似于:
<input type="file" name="pac_img_1">
<input type="file" name="pac_img_2">
<input type="file" name="pac_img_3">
他正在尝试获取这些图像。
我会做不同的事情。
HTML:
<input type="file" name="pac_img[]" />
<input type="file" name="pac_img[]" />
<input type="file" name="pac_img[]" />
(请注意,您可以动态添加文件输入而不必担心名称)
PHP:
if (count($_FILES['pac_img']) > 0){
echo("You have uploaded the following images:-<ul>");
foreach($_FILES['pac_img'] as $key => $file){
$target_path = "files/" . $companyName . "/images/";
$target_path = $target_path . basename( $file['name']);
if(move_uploaded_file($file['tmp_name'], $target_path)) {
echo "<li><a href='". $target_path . "'>". basename( $file['name'] ). "</a></li>";
} else{
echo "There was an error uploading an image";
}
}
echo("</ul>");
}else{
echo("None uploaded");
}
最后但并非最不重要的一点:始终检查上传的文件是否符合预期。 ( http://www.acunetix.com/websitesecurity/upload-forms-threat.htm )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.