上传PHP文件时出错

时间:2014-01-02 18:26:14

标签: php

我正在尝试打印多个文件的名称,但uploaded数组没有给我任何东西。我该怎么办?

<?php
    if (!empty($_FILES['file'])) {
        foreach ($_FILES['file']['name'] as $key => $name) {
            if ($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")) {
                $uploaded[] = $name;
            }
        }
        print_r($uploaded);
    }
?>

<!doctype html>

    <body>
        <div>
            <form action="" method="post" encype="multipart/form-data">
                <div>
                    <input type="file" name="file[]" multiple="multiple">
                    <input type="submit" value="Upload">
                </div>
            </form>
        </div>  
    </body>

1 个答案:

答案 0 :(得分:0)

我建议像这样重构你的代码;请注意添加两个array_key_exists检查以及$uploaded = array();以在循环之前初始化$uploaded数组:

<?php
    if(!empty($_FILES['file'])) {
        $uploaded = array();
        if (array_key_exists('name', $_FILES['file'])) {
            foreach($_FILES['file']['name'] as $key => $name) {
                if(array_key_exists('error', $_FILES['file']) $_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")) {
                    $uploaded[] = $name;
                }
            }
        }
        print_r($uploaded);
    }
?>

但我还建议在代码开头做一个非常基本的调试检查,以查看$_FILES是否包含任何内容:

<?php
    echo '<pre>';
    print_r($_FILES);
    echo '</pre>';
    if(!empty($_FILES['file'])) {
    …

但是查看您的HTML文件,您的<form action=""为空:

<form action="" method="post" encype="multipart/form-data">

如果将其更改为:

会发生什么
<form action="#" method="post" encype="multipart/form-data">

甚至get rid of the action entirely

<form method="post" encype="multipart/form-data">

我认为这是问题,因为您的表单是在HTML5中并且设置了action="",它永远不会起作用。具体来说是as outlined in the HTML5 spec

  

动作和格式内容属性(如果已指定)必须具有   可能由空格包围的有效URL值。