mic*_*urk 2 html php for-loop file-upload file
我使用以下HTML和PHP代码将多个图像移动到我的服务器.
有没有办法使用我的代码,我可以将特定的输入元素与上传的文件相关联?
所以在我的for循环中,我可以发现何时正在处理来自' image_22 ' 的图像.这可能使用我当前的代码吗?
Dream world将值"image_22"存储在变量$ imageNum中 :-)
这是我目前正在使用的片段......
HTML:
<input id="image_22" name="images[]" type="file" />
<input id="image_8" name="images[]" type="file" />
...
Run Code Online (Sandbox Code Playgroud)
PHP:
<?php
if (isset($_POST['Submit'])) {
$number_of_file_fields = 0;
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/uploaded/'; //set upload directory
/**
* we get a $_FILES['images'] array ,
* we procee this array while iterating with simple for loop
* you can check this array by print_r($_FILES['images']);
*/
for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
$number_of_file_fields++;
if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['images']['name'][$i];
if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory .
$_FILES['images']['name'][$i])) {
$number_of_moved_files++;
}
}
}
echo "Number of File fields created $number_of_file_fields.<br/> ";
echo "Number of files submitted $number_of_uploaded_files . <br/>";
echo "Number of successfully moved files $number_of_moved_files . <br/>";
echo "File Names are <br/>" . implode(',', $uploaded_files);
}
?>
Run Code Online (Sandbox Code Playgroud)
谢谢!!
在您的HTML中,只需在...中包含该值即可[].
<input id="image_22" name="images[22]" type="file" />
<input id="image_8" name="images[8]" type="file" />
Run Code Online (Sandbox Code Playgroud)
在循环中,使用foreach带索引,而不是增量for循环,这是PHP中比增量类型更常见的模式.在$index将在所提供的数量[]:
// Loop over the ['name'] key in $_FILES['images'] to get all the named indexes
foreach ($_FILES['images']['name'] as $index => $filename) {
if ($filename != '') {
// not empty...
$number_of_uploaded_files++;
// Check for validity (see below)...
// Use the name concatenated with _$index to supply store the index with the filename
$uploaded_files[] = $filename . "_$index";
if (move_uploaded_file($_FILES['images']['tmp_name'][$index], $upload_directory . $filename . "_$index")) {
// successful rename
$number_of_moved_files++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,您的脚本目前容易受到路径注入攻击.您必须过滤掉name每个文件的内容,../以防止文件系统中的任何位置(Web服务器可写)强制保存文件.建议使用可接受值的正则表达式检查名称:
// Verify that the uploaded filename contains only letters, numbers, hyphen, underscore, space before the `.` and letters only after the `.`
// You could also insist that it end in `.(jpg|gif|png)` or whatever your acceptable formats are
// Most important is to prevent things like `../`
if (preg_match('/^[a-z0-9_- ]+\.[a-z]+$/i', $filename)) {
// It's an ok filename
}
Run Code Online (Sandbox Code Playgroud)