This question already has answers here:
“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice: Undefined offset” using PHP
                                
                                    (28个答案)
                                
                        
                7年前关闭。
            
        

我收到一条错误消息,指出fileImage是此行上的未定义索引:$ idx = count($ _ POST ['fileImage'])-1;。现在发生这种情况是因为当用户打开页面时,显然没有任何内容发布到fileImage上,因此当什么都没有发布到$ _POST时,如何将其设置为“”?我以为我在下面的行中做到了,但似乎没有发生。

下面是代码:

<?php
session_start();

$idx = count($_POST ['fileImage']) -1 ;
$output = isset($_POST ['fileImage'][$idx]) ? $_POST ['fileImage'][$idx]['name'] : "";

?>


Javascript:

function stopImageUpload(success) {

    var imageNameArray = ['<?php echo $output ?>'];
    var result = '';

    if (success == 1) {
        result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
        for (var i = 0; i < imageNameArray.length; i++) {
            $('.listImage').append(imageNameArray[i] + '<br/>');
        }
    }
    else {
        result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
    }

    return true;
}​


以下是php脚本,该脚本在其中上传文件,该文件位于上述javascript函数的另一页上:

        <?php

            session_start();

            $result = 0;
            $errors = array ();
            $dirImage = "ImageFiles/";


        if (isset ( $_FILES ['fileImage'] ) && $_FILES ["fileImage"] ["error"] == UPLOAD_ERR_OK) {

        $fileName = $_FILES ['fileImage'] ['name'];

        $fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );
        $fileExt = strtolower ( $fileExt );


        $fileDst = $dirImage . DIRECTORY_SEPARATOR . $fileName;

                if (count ( $errors ) == 0) {
                    if (move_uploaded_file ( $fileTemp, $fileDst )) {
                        $result = 1;


                    }
                }

            }

    $_POST ['fileImage'][] = array('name' => $_FILES ['fileImage']['name']);

            ?>

        <script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result;?>);</script>

最佳答案

我看不到您要在哪里检查,但是这样做的方法是:

if(!isset($_POST['fileImage'))
      // Don't do something with the image
else
      // Totally do it

10-05 19:44