首页 > 解决方案 > 警告:explode() 期望参数 2 是字符串,给定 PHP 的数组

问题描述

我正在降低文件名并检查文件扩展名,explode()但我不断收到这两个错误:Warning: explode() expects parameter 2 to be string, array given在这一行:$tmp = explode('.', $_FILES['files']['name']);Warning: end() expects parameter 1 to be array, null given这一行$file_ext = strtolower(end ($tmp));(第二个来自第一个)。

我认为这是问题的$file_name = count($_FILES['files']['name']);具体count部分。因为这是一个文件上传脚本,我正在给某人一次上传多个图像的选项。当我单击上传按钮时,图像仍然会进入,但我只会收到这两个警告。我在这里尝试了所有其他答案,但没有一个对我有帮助,所以有什么建议吗?

$date_time = date('Y-m-d_H-i-s');
$errors = [];

if(isset($_POST['submit'])) {

    //if (isset($_POST['files'])) {

        $file_name = count($_FILES['files']['name']);
        $file_size = $_FILES['files']['size'];                       
        $file_type = $_FILES['files']['type'];
        $tmp = explode('.', $_FILES['files']['name']);
        $file_ext = strtolower(end ($tmp));

        $extensions = array("jpeg", "jpg", "png", "gif");

        if(in_array($file_ext, $extensions) === false) {

            $errors = "Only jpeg, jpg, png and gif files are allowed.";
        }

        if ($file_size > 95097152) {

            $errors = 'File cannot be larger than 1MB';
        }
    

        //$files = array_filter($_FILES['upload']['name']); //something like that to be used before processing files.

        // Count # of uploaded files in array
        //$total = count($_FILES['files']['name']);

        // Loop through each file
        for( $i=0 ; $i < $file_name ; $i++ ) {

            //Get the temp file path
            //$tmpFilePath = $_FILES['files']['tmp_name'][$i];
            $file_tmp = $_FILES['files']['tmp_name'][$i];

            //Make sure we have a file path
            if ($file_tmp != ""){

                    # code...

                
                //Setup our new file path
                $newFilePath = "./uploads/" . $_FILES['files']['name'][$i];

                //Upload the file into the temp dir
                if(move_uploaded_file($file_tmp, $newFilePath)) {

                    //Handle other code here

                }
            }
        }
    //}
}

标签: php

解决方案


从函数的第二个参数发出explode。你$_FILES['files']['name']不是一个字符串,但必须是。检查:

  1. var_dump($_FILES['files']['name']); 死('测试');
  2. 你会看到数组
  3. 您必须了解您需要哪个参数并将其用作第二个参数explode

PS 为了快速检查,您可以$_FILES['files']['name']手动编写一些字符串,例如 test.jpg

希望我的回答对你有所帮助。


推荐阅读