未定义的索引:PHP 中文件夹的扩展名


Undefined index: extension for folders in PHP

我想要一个脚本,可以将我的所有图像转换为缩略图,并将这些新缩略图保存在新文件夹中。我很幸运地找到了一个几乎完美运行的代码http://webcheatsheet.com/php/create_thumbnail_images.php

唯一的问题是,如果"uploads"文件夹(在代码末尾定义)中有一个文件夹,那么我得到"通知:未定义的索引:扩展名"。代码没有卡住,我仍然得到我的缩略图,但错误消息很烦人。

我试图放入一个 isset 函数,但做错了什么,因为我仍然无法阻止脚本对文件夹进行操作。代码对任何其他文件的反应都不一样,所以似乎是文件夹名称中缺少扩展名困扰了代码。

能够使它变得简单,只需从"上传"文件夹中删除任何文件夹并将缩略图的路径放在其他地方,但我也想让它在没有错误消息的情况下工作,以防我碰巧在这些图像文件夹中有文件夹。

// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image    
//print_r($info);   
if ( strtolower($info['extension']) == 'jpg' ) { // reacts on the folder with no extension name and gives an error
  echo "Creating thumbnail for {$fname} <br />";      
  // load image and get image size
  $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
  $width = imagesx( $img );
  $height = imagesy( $img );
  // calculate thumbnail size
  $new_width = $thumbWidth;
  $new_height = floor( $height * ( $thumbWidth / $width ) );
  // create a new temporary image
  $tmp_img = imagecreatetruecolor( $new_width, $new_height );
  // copy and resize old image into new image 
  imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
  // save thumbnail into a file
  imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
}

}

上面链接中的完整代码。

pathinfo 文档解释:

注意:

如果路径没有扩展名,则不会有扩展元素返回

<小时 />

因此,为了避免出现通知,您只需要在尝试使用它之前检查值是否可用:

if( isset($info['extension']) AND strtolower($info['extension']) == 'jpg'){
    //do sutff
}

或者您可以使用array_keys_exists('extension', $info)代替isset(...)