PHP实现oss签名生成及简单文件上传
获取访问域名
class OssFileClass
{
const AccessKeyId = '你自己的AccessKey';
const AccessKeySecret = '你自己的AccessKeySecret';
const BucketName = "你的存储空间名称";
/***
* 生成签名并调用上传接口
* @param array $upload_name 上传的文件名称及后缀数组
* @param string $path 文件的临时存储路径
* @param string $method 接口请求方式
* @return array 请求结果
*/
public static function requestWithAli( $upload_name , $path , $method ){
//文件后缀
$ext = strtolower( end( $upload_name ) );
//生成文件名称
$file_name = date( "YmdHis" ) . time() . vae_set_salt( 6 ) . ".{$ext}" ;
//请求地址,这里的OSS_URL可以查看上方的获取访问域名文档
$url = 'http://' . OSS_URL . "/{$file_name}";
//请求时间
$time = gmdate( "D, d M Y H:i:s" , time() ) . " GMT";
//这里根据业务需求自行决定content-type
//如果上传的是图片且需要直接可以查看到图片的content-type为image/文件后缀
//也可以使用下方获取content-type的方法
//通过getMimetype方法获取到的content-type访问图片时是直接下载的情况
$content_type = $ext == 'mp4' ? 'video/mp4' : "image/{$ext}";
//公共http请求头
$public_headers = [
'Accept-Encoding:',
'content-type:' . $content_type,
'content-length:' . filesize($path),
'host:' . OSS_URL,
'date:' . $time,
'Expect:'
];
// $public_headers = array_merge_recursive( $public_headers , $headers );
//签名参数
$params = [
'VERB' => $method, //表示HTTP请求的Method
// 'Content-MD5' => base64_encode(md5_file( $file, true)), //表示请求内容数据的MD5值,也可以为空
'Content-MD5' => '', //表示请求内容数据的MD5值,也可以为空
'Content-Type' => $content_type, //表示请求内容的类型
'Date' => $time, //表示此次操作的时间,且必须为GMT格式
// 'CanonicalizedOSSHeaders' => $ossHeaders, //表示以x-oss- 为前缀的HTTP Header的字典序排列
'CanonicalizedResource' => "/" . self::BucketName . "/{$file_name}" // 表示用户想要访问的OSS资源
];
//生成签名
$sign = base64_encode( hash_hmac( 'sha1' , implode( "\n" , array_values( $params )) , self::AccessKeySecret , true ));
$public_headers[] = "Authorization:OSS " . self::AccessKeyId . ":" . $sign;
//调用上传接口
$res = self::curlRequest( $url , '' , $public_headers , 'put' , $path );
//文件请求路径
$res['url'] = $url;
return $res;
}
/***
* @param string $name 文件名称
* @return string|null
*/
public static function getMimetype($name)
{
$parts = explode('.', $name);
if (count($parts) > 1) {
$ext = strtolower(end($parts));
if (isset(self::$mime_types[$ext])) {
return self::$mime_types[$ext];
}
}
return null;
}
private static $mime_types = [
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'apk' => 'application/vnd.android.package-archive',
'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'doc' => 'application/msword',
'ogg' => 'audio/ogg',
'pdf' => 'application/pdf',
'rtf' => 'text/rtf',
'mif' => 'application/vnd.mif',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'odc' => 'application/vnd.oasis.opendocument.chart',
'odb' => 'application/vnd.oasis.opendocument.database',
'odf' => 'application/vnd.oasis.opendocument.formula',
'odg' => 'application/vnd.oasis.opendocument.graphics',
'otg' => 'application/vnd.oasis.opendocument.graphics-template',
'odi' => 'application/vnd.oasis.opendocument.image',
'odp' => 'application/vnd.oasis.opendocument.presentation',
'otp' => 'application/vnd.oasis.opendocument.presentation-template',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
'odt' => 'application/vnd.oasis.opendocument.text',
'odm' => 'application/vnd.oasis.opendocument.text-master',
'ott' => 'application/vnd.oasis.opendocument.text-template',
'oth' => 'application/vnd.oasis.opendocument.text-web',
'sxw' => 'application/vnd.sun.xml.writer',
'stw' => 'application/vnd.sun.xml.writer.template',
'sxc' => 'application/vnd.sun.xml.calc',
'stc' => 'application/vnd.sun.xml.calc.template',
'sxd' => 'application/vnd.sun.xml.draw',
'std' => 'application/vnd.sun.xml.draw.template',
'sxi' => 'application/vnd.sun.xml.impress',
'sti' => 'application/vnd.sun.xml.impress.template',
'sxg' => 'application/vnd.sun.xml.writer.global',
'sxm' => 'application/vnd.sun.xml.math',
'sis' => 'application/vnd.symbian.install',
'wbxml' => 'application/vnd.wap.wbxml',
'wmlc' => 'application/vnd.wap.wmlc',
'wmlsc' => 'application/vnd.wap.wmlscriptc',
'bcpio' => 'application/x-bcpio',
'torrent' => 'application/x-bittorrent',
'bz2' => 'application/x-bzip2',
'vcd' => 'application/x-cdlink',
'pgn' => 'application/x-chess-pgn',
'cpio' => 'application/x-cpio',
'csh' => 'application/x-csh',
'dvi' => 'application/x-dvi',
'spl' => 'application/x-futuresplash',
'gtar' => 'application/x-gtar',
'hdf' => 'application/x-hdf',
'jar' => 'application/java-archive',
'jnlp' => 'application/x-java-jnlp-file',
'js' => 'application/javascript',
'json' => 'application/json',
'ksp' => 'application/x-kspread',
'chrt' => 'application/x-kchart',
'kil' => 'application/x-killustrator',
'latex' => 'application/x-latex',
'rpm' => 'application/x-rpm',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'tar' => 'application/x-tar',
'tcl' => 'application/x-tcl',
'tex' => 'application/x-tex',
'man' => 'application/x-troff-man',
'me' => 'application/x-troff-me',
'ms' => 'application/x-troff-ms',
'ustar' => 'application/x-ustar',
'src' => 'application/x-wais-source',
'zip' => 'application/zip',
'm3u' => 'audio/x-mpegurl',
'ra' => 'audio/x-pn-realaudio',
'wav' => 'audio/x-wav',
'wma' => 'audio/x-ms-wma',
'wax' => 'audio/x-ms-wax',
'pdb' => 'chemical/x-pdb',
'xyz' => 'chemical/x-xyz',
'bmp' => 'image/bmp',
'gif' => 'image/gif',
'ief' => 'image/ief',
'png' => 'image/png',
'wbmp' => 'image/vnd.wap.wbmp',
'ras' => 'image/x-cmu-raster',
'pnm' => 'image/x-portable-anymap',
'pbm' => 'image/x-portable-bitmap',
'pgm' => 'image/x-portable-graymap',
'ppm' => 'image/x-portable-pixmap',
'rgb' => 'image/x-rgb',
'xbm' => 'image/x-xbitmap',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'css' => 'text/css',
'rtx' => 'text/richtext',
'tsv' => 'text/tab-separated-values',
'jad' => 'text/vnd.sun.j2me.app-descriptor',
'wml' => 'text/vnd.wap.wml',
'wmls' => 'text/vnd.wap.wmlscript',
'etx' => 'text/x-setext',
'mxu' => 'video/vnd.mpegurl',
'flv' => 'video/x-flv',
'wm' => 'video/x-ms-wm',
'wmv' => 'video/x-ms-wmv',
'wmx' => 'video/x-ms-wmx',
'wvx' => 'video/x-ms-wvx',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'ice' => 'x-conference/x-cooltalk',
'3gp' => 'video/3gpp',
'ai' => 'application/postscript',
'aif' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'asc' => 'text/plain',
'atom' => 'application/atom+xml',
'au' => 'audio/basic',
'bin' => 'application/octet-stream',
'cdf' => 'application/x-netcdf',
'cgm' => 'image/cgm',
'class' => 'application/octet-stream',
'dcr' => 'application/x-director',
'dif' => 'video/x-dv',
'dir' => 'application/x-director',
'djv' => 'image/vnd.djvu',
'djvu' => 'image/vnd.djvu',
'dll' => 'application/octet-stream',
'dmg' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'dtd' => 'application/xml-dtd',
'dv' => 'video/x-dv',
'dxr' => 'application/x-director',
'eps' => 'application/postscript',
'exe' => 'application/octet-stream',
'ez' => 'application/andrew-inset',
'gram' => 'application/srgs',
'grxml' => 'application/srgs+xml',
'gz' => 'application/x-gzip',
'htm' => 'text/html',
'html' => 'text/html',
'ico' => 'image/x-icon',
'ics' => 'text/calendar',
'ifb' => 'text/calendar',
'iges' => 'model/iges',
'igs' => 'model/iges',
'jp2' => 'image/jp2',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'kar' => 'audio/midi',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'm4a' => 'audio/mp4a-latm',
'm4p' => 'audio/mp4a-latm',
'm4u' => 'video/vnd.mpegurl',
'm4v' => 'video/x-m4v',
'mac' => 'image/x-macpaint',
'mathml' => 'application/mathml+xml',
'mesh' => 'model/mesh',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mov' => 'video/quicktime',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'mp4' => 'video/mp4',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpga' => 'audio/mpeg',
'msh' => 'model/mesh',
'nc' => 'application/x-netcdf',
'oda' => 'application/oda',
'ogv' => 'video/ogv',
'pct' => 'image/pict',
'pic' => 'image/pict',
'pict' => 'image/pict',
'pnt' => 'image/x-macpaint',
'pntg' => 'image/x-macpaint',
'ps' => 'application/postscript',
'qt' => 'video/quicktime',
'qti' => 'image/x-quicktime',
'qtif' => 'image/x-quicktime',
'ram' => 'audio/x-pn-realaudio',
'rdf' => 'application/rdf+xml',
'rm' => 'application/vnd.rn-realmedia',
'roff' => 'application/x-troff',
'sgm' => 'text/sgml',
'sgml' => 'text/sgml',
'silo' => 'model/mesh',
'skd' => 'application/x-koan',
'skm' => 'application/x-koan',
'skp' => 'application/x-koan',
'skt' => 'application/x-koan',
'smi' => 'application/smil',
'smil' => 'application/smil',
'snd' => 'audio/basic',
'so' => 'application/octet-stream',
'svg' => 'image/svg+xml',
't' => 'application/x-troff',
'texi' => 'application/x-texinfo',
'texinfo' => 'application/x-texinfo',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'tr' => 'application/x-troff',
'txt' => 'text/plain',
'vrml' => 'model/vrml',
'vxml' => 'application/voicexml+xml',
'webm' => 'video/webm',
'webp' => 'image/webp',
'wrl' => 'model/vrml',
'xht' => 'application/xhtml+xml',
'xhtml' => 'application/xhtml+xml',
'xml' => 'application/xml',
'xsl' => 'application/xml',
'xslt' => 'application/xslt+xml',
'xul' => 'application/vnd.mozilla.xul+xml',
];
/***
* 发送curl请求
* @param string $url 请求地址
* @param string $data 携带的post数据
* @param string $header 请求头
* @param string $method 请求方式
* @param string $file 上传文件的路径
* @return array|bool|string 请求结果
*/
public static function curlRequest($url, $data = '',$header = '' , $method = 'post' , $file = '' )
{
$ch = curl_init();
$params[CURLOPT_URL] = $url; //请求url地址
$params[CURLOPT_REFERER] = $url; //
if( !empty($header) ) {
$params[CURLOPT_HTTPHEADER] = $header; //自定义header
}
$params[CURLOPT_HEADER] = false; //是否返回响应头信息
$params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
$params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
$params[CURLOPT_TIMEOUT] = 30; //超时时间
if(!empty($data)){
$params[CURLOPT_POSTFIELDS] = $data;
}
switch ($method){
case 'get':
break;
case 'post':
$params[CURLOPT_POST] = true;
break;
case 'put':
$params[CURLOPT_PUT] = true;
$params[CURLOPT_HEADER] = true;
curl_setopt($ch, CURLOPT_INFILE, fopen($file , 'rb'));
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file) );
curl_setopt($ch, CURLOPT_UPLOAD, true);
break;
}
$params[CURLOPT_SSL_VERIFYPEER] = false;//请求https时设置,还有其他解决方案
$params[CURLOPT_SSL_VERIFYHOST] = false;//请求https时,其他方案查看其他博文
//设置桥接(抓包)
// curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
curl_setopt_array($ch, $params); //传入curl参数
// curl_setopt($ch, CURLOPT_VERBOSE, true);//curl时debug信息
// 获得响应结果里的:头大小
// $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
//获取请求返回值
if( $method == 'put' ){
$content = self::handleHttpResponse( curl_exec($ch) ); //执行
} else {
$content = curl_exec($ch); //执行
}
// 根据头大小去获取头信息内容
// $header = substr($content, 0, $headerSize);
curl_close($ch); //关闭连接
return $content;
}
//处理http响应头字符串数据
private static function handleHttpResponse( $response = '' ){
if( empty($response) ){
return '';
}
//转换为数组形式
$strToArr = array_filter( explode( "\n" , $response ) );
array_pop( $strToArr );
//转换为key对value形式
$data = [];
foreach ( $strToArr as $k => $v ){
if( strpos( $v , ':') ){
$data[substr($v,0 , strpos($v,':'))] = str_replace( '"' , '' , substr($v,strpos($v,' ')) );
} else {
$data['code'] = substr($v , strpos( $v , ' ') , 4 );
}
}
return $data;
}
}