是这样的,我需要获取远程的图片,然后写入本地
但是有时候会出错误,比如获取了一个404之类的
现在 $str 是获取到的数据
那么如何判断 $str 是一个图片呢

解决方案 »

  1.   


    <?php
    $filename='filename';
    file_put_contents($filename,$str);
    if($imginfo = @getimagesize($filename)){
        //以下进行你要的处理
        echo "{$filename}是一张图片";
    }else{
        //以下进行不是图片文件的处理
        echo "{$filename}不是图片文件";
        @unlink($filename);
    }
      

  2.   

    404错误是没有找到你请求的资源。
    在确保请求的图片资源存在的前提下,
    可以通过判断获取http请求数据的contentType来判断其是否为图片,或者其它资源。当contentType包含image关键字的时候,就说明该资源是一个图片资源。<?php
    function contains($str, $content, $ignorecase=true)
    {
      if ($ignorecase)
      {
        $str = strtolower($str);
        $content = strtolower($content);
      }
      return strpos($content,$str) ? true : false;
    }$url='http://yourRequestUrl.com/';$fp=fopen($url,'r');
    //file_get_contents($url);$headerArray = $http_response_header;
    $contentType = null;foreach($headerArray as $value){
       if(contains('Content-Type',$value)){
           $contentType = explode(':',explode(';',$value)[0])[1];
       }
    }if($contentType!=null && contains("image",$contentType)){
       echo "This is a image resource";
    }
    ?>