'image/jpeg', '.png' => 'image/png', '.gif' => 'image/gif', '.bmp' => 'image/bmp' ); $curl = self::init( $url ); $result = curl_exec( $curl ); if ( curl_errno( $curl ) ) { curl_close( $curl ); return null; } $info = curl_getinfo( $curl ); curl_close( $curl ); if ( $result === false ) { return null; } if ( $info[ 'http_code' ] != 200 ) { return null; } $suffix = self::getSuffix( $info ); $filepath = tempnam( sys_get_temp_dir(), '' ); $file = fopen( $filepath, 'wb' ); if ( fwrite( $file, $result ) === false ) { fclose( $file ); return null; } fclose( $file ); return array ( 'filepath' => $filepath, 'suffix' => $suffix, 'mime' => $mime[ $suffix ] ); } /** * 根据给定的HTTP信息获取图片的后缀 * @param $info HTTP信息 * @return 找到的后缀名 */ private static function getSuffix ( &$info ) { $contentType = $info[ 'content_type' ]; $suf = array(); if ( !empty( $contentType ) && preg_match( '/(jpg|png|jpeg|gif|bmp)/i', $contentType, $suf ) === 1 ) { return "." . str_replace( "jpeg", "jpg", strtolower( $suf[ 0 ] ) ); } if ( preg_match( '/(jpg|png|jpeg|gif|bmp)/i', $info[ 'url' ], $suf ) === 1 ) { return "." . str_replace( "jpeg", "jpg", strtolower( $suf[ 0 ] ) ); } return ".jpg"; } }