上传图像时为foreach()提供的参数无效

时间:2014-09-09 15:47:19

标签: php html image foreach upload

我有一些裁剪的PHP代码。而且我遇到了一些问题。

我可以上传一些图片,有些图片不能上传。我不知道为什么。

如果我无法上传图片,则会显示错误:

Warning: Invalid argument supplied for foreach() in...

我不知道为什么,需要帮助

PHP

<?php
session_start();
$valid_formats = array("jpg", "png", "gif", "JPG", "PNG", "GIF");
$max_file_size = 1024*3000; //3 MB
$path = "uploads/"; // Upload directory
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
    // Loop $_FILES to exeicute all files
    foreach ($_FILES['files']['name'] as $f => $name) {     
        if ($_FILES['files']['error'][$f] == 4) {
            continue; // Skip file if any error found
        }          
        if ($_FILES['files']['error'][$f] == 0) {              
            if ($_FILES['files']['size'][$f] > $max_file_size) {
                $message[] = "$name is too large!.";
                continue; // Skip large files
            }
            elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
                $message[] = "$name is not a valid format";
                continue; // Skip invalid file formats
            }
            else{ // No error found! Move uploaded files 
                $kaboom = explode(".",$name);
                $fileExt = end($kaboom);
                $target_file = "uploads/$name";
                $thumbnail = "uploads/thumb_$name";

                $image_info = getimagesize($_FILES['files']['tmp_name'][$f]);
                $image_width = $image_info[0];
                $image_height = $image_info[1];

                $canvas = imagecreatetruecolor('1000', '800');
                $current_image = imagecreatefromjpeg($_FILES['files']['tmp_name'][$f]);
                imagecopy($canvas, $current_image, 0, 0, $width/2, $height/2, '1000', '800');
                imagejpeg($canvas, $path.$name.'_cropped.jpg', 100);
            }
        }
    }
}
?>

当我把:

echo '<pre>'; var_dump($_FILES); echo '</pre>';

显示:

array(1) {
  'files' =>
  array(5) {
    'name' =>
    array(2) {
      [0] =>
      string(12) "IMG_1281.JPG"
      [1] =>
      string(12) "IMG_1282.JPG"
    }
    'type' =>
    array(2) {
      [0] =>
      string(0) ""
      [1] =>
      string(10) "image/jpeg"
    }
    'tmp_name' =>
    array(2) {
      [0] =>
      string(0) ""
      [1] =>
      string(23) "D:\wamp\tmp\phpF735.tmp"
    }
    'error' =>
    array(2) {
      [0] =>
      int(1)
      [1] =>
      int(0)
    }
    'size' =>
    array(2) {
      [0] =>
      int(0)
      [1] =>
      int(453437)
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您是否已在html中检查了文件输入的外观?

Foreach期望数组中的值,因此如果您的表单使用enctype =“multipart / form-data”提交,并且您的文件输入如下所示,那么您应该没有问题。

<input type="file" name="files[]" />

如果这解决了任何问题,请告诉我