Commit db1454e6 by 杨树贤

初始化项目

parents
Showing with 4844 additions and 0 deletions

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

APP_ENV=local
APP_DEBUG=true
APP_KEY=
APP_TIMEZONE=UTC
SYSTEM_CODE=03
SYSTEM_NAME=商品Api
ELK_NAME=ic_goods_api
GoodsInfoUrl=http://192.168.2.232:61002
ES_URL=http://soapi.icsales.com:8001
authapi=http://authapi.icsales.cc
DB_CONNECTION=mysql
DB_HOST=192.168.2.232
DB_PORT=3306
DB_DATABASE=ic_data
DB_USERNAME=ic_data
DB_PASSWORD=ic_data#zsyM
DB_PREFIX=ic_
REDIS_HOST=192.168.1.235
REDIS_PASSWORD=icDb29mLy2s
REDIS_PORT=6379
REDIS_READ_HOST=192.168.1.235
REDIS_READ_PASSWORD=icDb29mLy2s
REDIS_READ_PORT=6379
CACHE_DRIVER=file
QUEUE_DRIVER=sync
login=http://authapi.icsales.cc
APP_ENV=local
APP_DEBUG=true
APP_KEY=
APP_TIMEZONE=UTC
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
CACHE_DRIVER=file
QUEUE_DRIVER=sync
/.idea
Homestead.json
Homestead.yaml
storage/logs
[submodule "common"]
path = common
url = ssh://git@119.23.72.7:22611/yyc/Common.git
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Laravel\Lumen\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//
}
}
<?php
namespace App\Events;
use Illuminate\Queue\SerializesModels;
abstract class Event
{
use SerializesModels;
}
<?php
namespace App\Events;
class ExampleEvent extends Event
{
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
}
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
return parent::render($request, $e);
}
}
<?php
namespace App\Http\Controllers;
use App\Model\GoodsModel;
use App\Model\UploadGoodsModel;
use Illuminate\Http\Request;
class ApiController extends Controller
{
public function GoodsInfo(Request $request){
$Field = ['goods_name/like','status/eq','start_time','end_time','goods_id/eq','user_id/eq','offset','p'];
$collert = TrimX($Field);
if(!empty($collert['start_time'])){
$collert['start_time'] = strtotime($collert['start_time']);
$collert['update_time/gt'] = $collert['start_time'];
unset($collert['start_time']);
}
if(!empty($collert['end_time'])){
$collert['end_time'] = strtotime($collert['end_time']);
$collert['update_time/lt'] = $collert['end_time'];
unset($collert['end_time']);
}
//设置有图片的优先
$collert ['goods_images/order'] = 'desc';
if(!empty($request->user->user_id))
$collert['user_id'] = $request->user->user_id;
else{
$collert['status/eq'] = 1;
$collert['audit_status/eq'] = 1;
}
$GoodsModel = new GoodsModel();
$result = $GoodsModel->FindGoods($collert);
if(!$result)
return $this->Export(ErrorCode(001,1),'没有数据');
return $this->Export(0,'ok',$result);
}
public function AddGoods(Request $request){
$Filed = ['goods_name','brand_name','encap','price','stock','delivery_time','is_auto','goods_images','source',
'currency','ladder_price'];
$collert = TrimX($Filed,true);
$MustFile = [
'goods_name'=> [
'errcode'=>005,'errmsg'=>'请输入商品型号'
], 'brand_name'=>[
'errcode'=>002,'errmsg'=>'请输入品牌'
],'delivery_time'=>[
'errcode'=>003,'errmsg'=>'请输入货期'
],'stock'=>[
'errcode'=>004,'errmsg'=>'请输入库存'
]];
foreach ($MustFile as $k=>$v)
if(empty($collert[$k])) return $this->Export(ErrorCode($v['errcode'],1),$v['errmsg']);
$collert['user_id'] = $request->user->user_id;
$GoodsModel = new GoodsModel();
$result = $GoodsModel->AddGoods($collert);
if($result === false)
return $this->Export(ErrorCode(001,5),'新增失败');
if($result !== true)
return $this->Export(ErrorCode(006,1),'新增失败');
return $this->Export(0,'新增成功');
}
public function SaveGoods($request){
$Filed = ['goods_name','brand_name','encap','price','stock','delivery_time','is_auto','goods_images',
'currency','ladder_price','goods_id'];
$collert = TrimX($Filed);
if(empty($collert['goods_id'])) return $this->Export(ErrorCode(010,1),'请选择要编辑的商品');
$GoodsModel = new GoodsModel();
$result = $GoodsModel ->GoodsInfo($collert['goods_id']);
if(!$result || empty($result[$collert['goods_id']]))
return $this->Export(ErrorCode(002,5),'没有查找到这个型号');
if($result[$collert['goods_id']]['user_id'] != $request->user->user_id)
return $this->Export(ErrorCode(8,1),'没有编辑这个商品的权限');
$result = $GoodsModel->SaveGoods($collert);
if($result === false)
return $this->Export(ErrorCode(003,5),'编辑失败');
if($result !== true)
return $this->Export(ErrorCode(9,1),'编辑失败');
return $this->Export(0,'ok','新增成功');
}
public function GoodsStatus(Request $request){
$collert = TrimX(['goods_id','status']);
$MustField = ['goods_id'=>'未选择商品','status'=>'未选择操作状态'];
foreach ($MustField as $k=>$v)
if(empty($collert[$k]))
return $this->Export(ErrorCode(004,1),$v);
$MustFile = [
'goods_id'=> [
'errcode'=>010,'errmsg'=>'请选择商品'
], 'status'=>[
'errcode'=>011,'errmsg'=>'未选择操作状态'
]];
foreach ($MustFile as $k=>$v)
if(empty($collert[$k])) return $this->Export(ErrorCode($v['errcode'],1),$v['errmsg']);
$Url = config('website.GoodsInfoUrl').'/goods/status';
$collert['user_id'] = $request->user->user_id;
$result = reportCurl($Url,$collert,true);
$result = json_decode($result,true);
if(!isset($result['errcode']) || empty($result['data']))
return $this->Export(ErrorCode(004,5),'操作失败');
if($result['errcode'] !==0 )
return $this->Export(ErrorCode(005,5),'数据异常,操作失败');
if(is_string($collert['goods_id'])){
if(empty($result['data'][$collert['goods_id']]) && $result['data'][$collert['goods_id']] !==true )
return $this->Export(ErrorCode(006,5),'操作失败');
return $this->Export(0,'操作成功');
}else{
$Fail=0;
$su=0;
foreach ($collert['goods_id'] as $k=>$v){
if(empty($result['data'][$v]) || $result['data'][$v] !==true )
$Fail++;
else $su++;
}
if($su > 0){
if($Fail === 0) return $this->Export(0,'操作成功');
else return $this->Export(0,'操作成功数量:'.$su.',操作失败数量:'.$Fail,['data'=>$result['data']]);
} else{
return $this->Export(ErrorCode(007,5),'操作失败',['data'=>$result['data']]);
}
}
}
public function MysqlGoodsCount(Request $request){
$data['count']['mygoods'] = 0;
$data['count']['newadd'] = 0;
$data['count']['imperfect'] = 0;
$map['user_id/eq'] = $request->user->user_id;
$Url = config('website.ES_URL').'/search/get_data';
$result = reportCurl($Url,$map,true);
$result = json_decode($result,true);
if(!empty($result['data']['total']))
$data['count']['mygoods'] = $result['data']['total'];
$map['add_time/gt'] = mktime(0,0,0,date('m'),date('d')-date('w')+1,date('Y'));//本周0点
$result = json_decode(reportCurl($Url,$map,true),true);
if(!empty($result['data']['total']))
$data['count']['newadd'] = $result['data']['total'];
unset($map['add_time/gt']);
$map['goods_images/eq'] = 2;//1是有图,2是没图
$result = json_decode(reportCurl($Url,$map,true),true);
if(!empty($result['data']['total']))
$data['count']['imperfect'] = $result['data']['total'];
return $this->Export(0,'ok',$data);
}
public function UploadGoods(Request $request)
{
$file = $request->file('file');
if($file -> isValid()) {
$realPath = $file -> getRealPath();
$data['user_id'] = $request->user->user_id;
$Model = new UploadGoodsModel();
$ID = 0;
$result = $Model->UploadGoods($data,$realPath,$ID);
if(!$result)
return $this->Export(ErrorCode(8,5),'上传失败');
if($result !== true)
return $this->Export(ErrorCode(010,1),'上传失败');
$Url = config('website.GoodsInfoUrl').'/goods/task';
$map['user_id'] = $request->user->user_id;
$map['id'] = $ID;
$result = reportCurl($Url,$map,true);
$result = json_decode($result,true);
if(!isset($result['errcode']) || $result['errcode'] !== 0)
return $this->Export(ErrorCode(9,5),'推送任务失败,请联系客服处理');
return $this->Export(0,'上传成功,请等待处理结果');
}else
return $this->Export(ErrorCode(011,1),'没有上传文件');
}
public function UploadGoodsList(Request $request){
$collert = TrimX(['start_time','end_time','limit']);
if(!empty($collert['start_time'])){
$collert['start_time'] = strtotime($collert['start_time']);
$collert['update_time/gt'] = $collert['start_time'];
unset($collert['start_time']);
}
if(!empty($collert['end_time'])){
$collert['end_time'] = strtotime($collert['end_time']);
$collert['update_time/lt'] = $collert['end_time'];
unset($collert['end_time']);
}
if(!empty($collert['limit'])){
$limit = $collert['limit'];
unset($collert['limit']);
}else $limit = 10;
$collert['user_id'] = $request->user->user_id;
$Model = new UploadGoodsModel();
$result = $Model->UploadGoodsList($collert,$limit);
return $this->Export(0,'ok',$result);
}
}
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
use Hprose\Http\Client;
class Controller extends BaseController
{
public function Export( $Errcode=0,$ErrMsg='', $dataArr=[])
{
return Export($Errcode,$ErrMsg, $dataArr);
}
/**
* 内部免验证通过
* @return [type] [description]
*/
protected function auth($request)
{
$k1 = $request->input('k1', '');
$k2 = $request->input('k2', '');
$key = Config('alioss.SUPER_AUTH_KEY');
if (!empty($k1) && $k1 < time() - 600) {
return false;
}
$pwd = pwdhash($k1, $key);
if ($k2 == $pwd) {
return true;
} else {
return false;
}
}
// 登录校验
protected function checkLogin($request)
{
$token = $request->input('token', '');
if (empty($token)) return $this->_json(ErrorCode(001, 1));
try {
$url = config('website.authapi').'/hprose/service';
$user = new Client($url, false);
$user->setHeader("Authorization",'Bearer '.$token);
$res = $user->getUserInfo();
$user->close();
} catch (Exception $e) {
return $this->_json(ErrorCode(002, 1));
}
if ($res['errcode'] != 0) return $this->_json(ErrorCode(003, 1));
return $this->_json(0, '', $res['data']);
}
/**
* 返回数据
* @param [Integer] $code [状态码]
* @param [String] $message [信息]
* @param [String] $data [数据]
* @return [Json]
*/
public function _json($code, $message='', $data=array())
{
if ($code != 0) {
ErrorLog($code, $message); // 记录到logreport
}
return ['errcode'=>$code, 'errmsg'=>$message, 'data'=>$data];
}
}
<?php
namespace App\Http\Controllers;
class ExampleController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
//
}
//
}
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
class Authenticate
{
/**
* The authentication guard factory instance.
*
* @var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Auth\Factory $auth
* @return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if ($this->auth->guard($guard)->guest()) {
return response('Unauthorized.', 401);
}
return $next($request);
}
}
<?php
namespace App\Http\Middleware;
use Closure;
use Hprose\Http\Client;
class CheckLogin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//获取token
$Token = $request->input('token');
if(empty($Token))
return Response(Export(-1,'no access'));
$Url = config('website.authapi').'/hprose/service';
$user = new Client($Url,false);
$user->setHeader("Authorization",'Bearer '.$Token);
$result = $user->getUserInfo();
if(!$result || !isset($result['errcode']))
return Response(Export(-3,'登录信息获取失败'));
if($result['errcode'] !== 0)
return Response(Export($result['errcode'],$result['errmsg']));//原样返回到前端
if(empty($result['data']['user_id']))
return Response(Export(-4,'登录信息获取失败'));
$request->user = '';
$User = $result['data'];
$request->user = (object)$User;
return $next($request);
}
}
<?php
namespace App\Http\Middleware;
use Closure;
class ExampleMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
}
<?php
namespace App\Http\Middleware;
use Closure;
use App\Model\TokenModel;
class UniqueMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//设置唯一追踪值
$request->offsetSet('unique', getUnique(true));
return $next($request);
}
}
<?php
namespace App\Http\Middleware;
use Closure;
class web
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$request->user = '';
$response = $next($request);
$origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '';
$allow_origin = config('website.allow_origin');
if (in_array($origin, $allow_origin)) {
$response->header('Access-Control-Allow-Origin', $origin);
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
$response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
$response->header('Access-Control-Allow-Credentials', 'true');
}
return $response;
}
}
<?php
/**
* Created by PhpStorm.
* User: ICHUNT
* Date: 2019-06-18
* Time: 16:51
*/
function ErrorCode($code = 0, $level = 1){
$systemcode = config('website.SystemCode');
return errCode($code , $level , $systemcode);
}
function Export($Errcode=0,$ErrMsg='', $dataArr=[]){
if(!empty($dataArr) && !is_array($dataArr)) {
$Errcode = -2;
$ErrMsg = '系统错误';
}
$domain = \Illuminate\Support\Facades\Request::server('HTTP_HOST');//获取当前域名
$cofig = config('website.language');
if(!empty($cofig[$domain])){//配置了域名的版本
$language = $cofig[$domain];
}
if(!empty($language)){
$errInfo = config('language.'.$language.'.'.$Errcode);
$ErrMsg = $errInfo;
}
$data=['errcode'=>$Errcode, 'errmsg'=>$ErrMsg];
if(($data['errcode'] < 10000 || $data['errcode'] >= 50000) && $data['errcode'] !==0 )//非正常返回码,上报
ErrorLog($Errcode,$ErrMsg);
if(!empty($dataArr)) foreach ($dataArr as $k=>$v) $data[$k]=$v;
$callback = \Illuminate\Support\Facades\Request::only('callback');
$data = json_encode($data);
if(!empty($callback['callback']))
return $callback['callback'].'('.$data.')';
$IE8 = \Illuminate\Support\Facades\Request::only('ie8');
if(!empty($IE8['ie8']))
$data = '<script>document.domain="'.$IE8['ie8'].'"</script>'.$data;
return $data;
}
/**
* 取得根域名
* @param type $domain 域名
* @return string 返回根域名
*/
function GetUrlToDomain($domain='') {
if(empty($domain))
$domain = \Illuminate\Support\Facades\Request::server('HTTP_HOST');
$domain_postfix_cn_array = array("com", "net", "org", "gov", "edu", "com.cn", "cn");
$array_domain = explode(".", $domain);
$array_num = count($array_domain) - 1;
if ($array_domain[$array_num] == 'cn') {
if (in_array($array_domain[$array_num - 1], $domain_postfix_cn_array)) {
$re_domain = $array_domain[$array_num - 2] . "." . $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
} else {
$re_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
}
} else {
$re_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
}
return $re_domain;
}
/**
* 统一密码加密
* @param [type] $pwd [description]
* @return [type] [description]
*/
function pwdhash($pwd, $salt)
{
return md5(md5($pwd) . $salt);
}
//生成的文件上传到OSS
function SaveDownFile($path=''){
if(empty($path)) return false;
$result=json_decode(UploadToOss($path),true);
if(empty($result['code']) || $result['code'] != 200 || empty($result['data'][0])) return false;
return $result['data'][0];
}
/**
* php上传文件到oss
* @param string $Path 文件路径
* @param array $data
* @return array
* Created on 2018-03-15
*/
function UploadToOss($Path='',$data=[]){
if(empty($Path)) return false;
$field=new CurlFile($Path);
if(!$field) return false;
$data['upload']=$field;
$url=config('website.UploadUrl');
$data['source']=1;
$data['k1']=time();
$data['k2']=MD5(MD5($data['k1']).config('website.UploadKey'));
$data['FileType']='csv';
$result=curlCurlFile($url,$data);
return $result;
}
function curlCurlFile($url, $params = false, $ispost = 1, $header=[], &$httpInfo = [])
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
if(!empty($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
if ($ispost) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_URL, $url);
} else {
if ($params) {
curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
}
$response = curl_exec($ch);
$httpInfo = curl_getinfo($ch);
if ($response === FALSE) {
// echo "cURL Error: " . curl_error($ch);
return false;
}
curl_close($ch);
return $response;
}
\ No newline at end of file
<?php
namespace App\Jobs;
class ExampleJob extends Job
{
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
//
}
}
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
abstract class Job implements ShouldQueue
{
/*
|--------------------------------------------------------------------------
| Queueable Jobs
|--------------------------------------------------------------------------
|
| This job base class provides a central location to place any logic that
| is shared across all of your jobs. The trait included with the class
| provides access to the "queueOn" and "delay" queue helper methods.
|
*/
use InteractsWithQueue, Queueable, SerializesModels;
}
<?php
namespace App\Listeners;
use App\Events\ExampleEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class ExampleListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param ExampleEvent $event
* @return void
*/
public function handle(ExampleEvent $event)
{
//
}
}
<?php
namespace App\Model;
use Common\Model\RedisModel;
use Illuminate\Database\Eloquent\Model;
use Maatwebsite\Excel\Facades\Excel;
class ExcelModel extends Model
{
protected $connection=false;
protected $table=false;
public $timestamps = false;
public function HdExcel($Url,$ID){
$result = false;
Excel::load($Url,function($reader) use(&$result,$ID){
$reader->takeRows(config('website.upload_goods_num')+2);
$title = config('website.upload_goods_title');
$reader->takeColumns(count($title));
$reader->first();
$reader = $reader->toArray();
if(empty($reader) || empty($reader[0]) || empty($reader[1]))
return $result = '没有上传数据';
foreach ($title as $k=>$v){
if($v != $reader[1][$k])
return $result = '表头'.$v.'不匹配,请使用模板上传';
}
unset($reader[0],$reader[1]);
if(empty($reader))
return $result = '没有上传数据';
foreach ($reader as $k=>$v){
if((empty($v[0]) && empty($v[1])) || ($v[0] == 'null' && $v[1] == 'null'))
unset($reader[$k]);
}
$Redis = new RedisModel();
$RedisReturn = $Redis->hset('ic_upload_goods',$ID,json_encode($reader));
if($RedisReturn === false) return $result = false;
return $result = true;
}, 'UTF-8');
unlink($Url);
if($result === true)
return true;
return $result;
}
}
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class GoodsModel extends Model
{
protected $connection=false;
protected $table=false;
public $timestamps = false;
public function FindGoods($map){
$Url = config('website.ES_URL').'/search/get_data';
$result = reportCurl($Url,$map,true);
$result = json_decode($result,true);
if(empty($result) || !isset($result['errcode']) || $result['errcode']!==0 || empty($result['data']['goods_id']))
return false;
$total = $result['data']['total'];
$result = $this->GoodsInfo($result['data']['goods_id']);
if(!$result) return false;
$data['goods_list'] = $result;
$data['total'] = $total;
return $data;
}
public function GoodsInfo($GoodsId){
$GoodsInfoUrl = config('website.GoodsInfoUrl').'/goods/info';
$map['goods_id'] = $GoodsId;
$result = reportCurl($GoodsInfoUrl,$map,true);
$result = json_decode($result,true);
if(!$result || !isset($result['errcode']) || empty($result['goods_list']))
return false;
return $result['goods_list'];
}
public function AddGoods($info){
$Url = config('website.GoodsInfoUrl').'/goods/add';
$result = json_decode(reportCurl($Url,$info,true),true);
if(empty($result) || !isset($result['errcode']))
return false;
if($result['errcode'] === 0)
return true;
return $result['errmsg'];
}
public function SaveGoods($info){
$Url = config('website.GoodsInfoUrl').'/goods/save';
$result = json_decode(reportCurl($Url,$info,true),true);
if(empty($result) || !isset($result['errcode']))
return false;
if($result['errcode'] === 0)
return true;
return $result['errmsg'];
}
}
<?php
namespace App\Model\Oss;
use Illuminate\Database\Eloquent\Model;
class FileModel
{
protected $allowDocMaxSize = 20*1024*1024; // 20M
protected $allowAudioMaxSize = 30*1024*1024; // 50M
protected $allowVideoMaxSize = 50*1024*1024; // 50M
/**
* 文件类型
* @param [String] $fileType [MIME]
* @return [String]
*/
public function fileType($fileType)
{
switch ($fileType) {
case 'image/jpeg':
case 'image/pjpeg': // ie6-8
case 'image/png':
case 'image/x-png': // ie6-8
case 'image/gif':
case 'image/bmp':
return 'images';
break;
case 'application/msword':
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
return 'doc/word';
break;
case 'application/vnd.ms-excel':
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
case 'text/comma-separated-values': // csv
case 'text/csv':
case '.csv':
return 'doc/excel';
break;
case 'application/vnd.ms-powerpoint':
case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
return 'doc/ppt';
break;
case 'application/pdf':
return 'doc/pdf';
break;
case 'text/plain':
return 'doc/txt';
break;
case 'application/zip':
return 'doc/zip';
break;
case 'video/avi':
case 'video/x-ms-wmv';
case 'application/vnd.rn-realmedia-vbr':
case 'application/octet-stream':
return 'video';
break;
case 'audio/mpeg':
case 'audio/mpeg3':
case 'audio/x-mpeg-3':
case 'audio/x-mpeg':
case 'audio/mp3':
return 'audio/mp3';
break;
case 'audio/x-wav':
return 'audio/wmv';
break;
default:
return false;
break;
}
}
/**
* 检查文件大小
* @param [Integer] $size [文件大小]
* @return [Boolen]
*/
public function checkDocSize($size)
{
if ($size > $this->allowDocMaxSize) {
return false;
} else {
return true;
}
}
// 检查视频大小
public function checkVideoSize($size)
{
if ($size > $this->allowVideoMaxSize) {
return false;
} else {
return true;
}
}
// 检查音频大小
public function checkAudioSize($size)
{
if ($size > $this->allowAudioMaxSize) {
return false;
} else {
return true;
}
}
}
\ No newline at end of file
<?php
namespace App\Model\Oss;
use Illuminate\Database\Eloquent\Model;
class ImageModel
{
protected $allowExt = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
protected $allowMaxSize = 2*1024*1024; // 2M
/**
* 检查图片后缀名
* @param [String] $ext [图片后缀]
* @return [Boolen]
*/
public function checkImageExt($ext)
{
if (in_array(strtolower($ext), $this->allowExt)) {
return true;
} else {
return false;
}
}
/**
* 检查图片大小
* @param [Integer] $size [图片大小]
* @return [Boolen]
*/
public function checkImageSize($size)
{
if ($size > $this->allowMaxSize) {
return false;
} else {
return true;
}
}
}
\ No newline at end of file
<?php
namespace App\Model\Oss;
use Illuminate\Database\Eloquent\Model;
class UploadLogModel extends Model
{
protected $table = 'upload_log';
protected $primaryKey = 'log_id';
public $timestamps = false;
}
\ No newline at end of file
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use DB;
class UploadGoodsModel extends Model
{
protected $table='upload_goods';
public $timestamps = false;
public function UploadGoods($data,$realPath,&$ID=0){
DB::connection($this->connection)->beginTransaction();
$data['update_time'] = time();
$data['add_time'] = $data['update_time'];
$result = $this->insertGetId($data);
if(!$result)
return false;
$ID = $result;
$Model = new ExcelModel();
$result = $Model->HdExcel($realPath,$result);
if($result !== true)
return $result;
DB::connection($this->connection)->commit();
return true;
}
public function UploadGoodsList($map,$limit){
$list = $this->where($map)->select('id','add_time','update_time','status','file_info','loginfo')
->orderBy('id','desc')
->paginate($limit)->toArray();
if(!$list)
return false;
$status = config('config.upload_goods_status');
foreach ($list['data'] as $k=>&$v){
$v['status'] = $status[$v['status']];
$v['add_time'] = date('Y-m-d H:i',$v['add_time']);
$v['update_time'] = date('Y-m-d H:i',$v['update_time']);
$v['file_info'] = json_decode($v['file_info'],true);
}
return $list;
}
}
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
<?php
namespace App\Providers;
use App\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Boot the authentication services for the application.
*
* @return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
$this->app['auth']->viaRequest('api', function ($request) {
if ($request->input('api_token')) {
return User::where('api_token', $request->input('api_token'))->first();
}
});
}
}
<?php
namespace App\Providers;
use Laravel\Lumen\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
];
}
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password',
];
}
#!/usr/bin/env php
<?php
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| First we need to get an application instance. This creates an instance
| of the application / container and bootstraps the application so it
| is ready to receive HTTP / Console requests from the environment.
|
*/
$app = require __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(
'Illuminate\Contracts\Console\Kernel'
);
exit($kernel->handle(new ArgvInput, new ConsoleOutput));
<?php
require_once __DIR__.'/../vendor/autoload.php';
try {
(new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
//
}
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/
$app = new Laravel\Lumen\Application(
realpath(__DIR__.'/../')
);
$app->withFacades();
$app->withEloquent();
/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
// App\Exceptions\Handler::class
Common\Exceptions\Handler::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/
$app->middleware([
// App\Http\Middleware\ExampleMiddleware::class
App\Http\Middleware\UniqueMiddleware::class
]);
$app->routeMiddleware([
'web' => App\Http\Middleware\web::class,
'login' => App\Http\Middleware\CheckLogin::class,
]);
/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/
// $app->register(App\Providers\AppServiceProvider::class);
// $app->register(App\Providers\AuthServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);
$app->register(Illuminate\Redis\RedisServiceProvider::class);
$app->register(Maatwebsite\Excel\ExcelServiceProvider::class);
/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/
$app->configure('website');
$app->configure('database');
$app->configure('alioss');
$app->configure('language');
$app->configure('excel');
$app->configure('config');
LogReport::$suffix = '_'.env('LARAVELS_LISTEN_PORT', '');
LogReport::$app_name = 'ic_goods_api';
LogReport::$log_path = realpath(__DIR__ . '/../').'/storage/logs/LogReport/';
require_once __DIR__.'/../app/Http/function.php';
$app->router->group([
'namespace' => 'App\Http\Controllers',
], function ($router) {
require __DIR__.'/../routes/web.php';
});
return $app;
<?php
namespace Common\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use PDOException;
use Predis\Connection\ConnectionException;
use Symfony\Component\Debug\Exception\FatalThrowableError;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
$report = [
'code' => $this->getCode($e),
'message' => toUtf8($e->getMessage()),
'file' => $e->getFile(),
'line' => $e->getLine(),
'request' => json_encode(Request::input()),
'apiUrl' => Request::url(),
'uniqid' => getUnique(true),
];
\LogReport::write(\LogReport::anlyError($report));
if (!env('APP_DEBUG')) {
SendAlarm($e,config('website.SystemName'));
}
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
$code = $this->getCode($e);
//自动区分错误编码返回内容
if (strlen($code) == 6 && substr($code, 0, 1) == 1) {
return Response()->json(['errcode' => $code, 'errmsg' => toUtf8($e->getMessage())]);
}
$msg = '系统错误,请联系客服处理';
$data = '';
if (env('APP_DEBUG')) {
$msg = toUtf8($e->getMessage());
$log = [toUtf8($e->getMessage()), $e->getFile(), $e->getLine()];
$data = implode(" ", $log);
}
return Response()->json(['errcode' => $code, 'errmsg' => $msg.' #'.getUnique(true), 'data' => $data]);
// return parent::render($request, $e);
}
private function getCode($e)
{
$systemcode = config('website.SystemCode');
if ($e instanceof PDOException) {//数据库连接
$code = errCode(001, 9, $systemcode);
} elseif ($e instanceof ConnectionException) {//redis连接
$code = errCode(002, 9, $systemcode);
} elseif ($e instanceof FatalThrowableError) {//致命错误
$code = errCode(003, 9, $systemcode);
} elseif ($e instanceof NotFoundHttpException) {//404
$code = 404;
} else {
$code = $e->getCode() ? $e->getCode() : '';
}
return $code;
}
}
<?php
//日志目录位置
defined('REPORT_LOG_PATH') or define('REPORT_LOG_PATH', $_SERVER['DOCUMENT_ROOT'].'/Application/Runtime/LogReport/');
//项目名
defined('REPORT_APP_NAME') or define('REPORT_APP_NAME', 'api');
//单日志文件大小限制
defined('LOG_FILE_SIZE') or define('LOG_FILE_SIZE', 2097152); //2MB
//旧日志清理天数差
defined('REPORT_CLEAR_DAY_DIFF') or define('REPORT_CLEAR_DAY_DIFF', 7); //7天前
//旧数据触发清空时间条件
defined('REPORT_CLEAR_TIME') or define('REPORT_CLEAR_TIME', '9,10,11'); //9-11点
// 设定错误和异常处理
error_reporting(0);
LogReport::auto();
class LogReport
{
static $logtime = null;
static $handler = [
'finally_except' => ['Think\Think', 'appException'],
'finally_error' => ['Think\Think', 'appError'],
];
static $suffix = '';
static $log_path = '';
static $app_name = '';
static $data = [
'msg' => '',// 错误信息
'msgCode' => '',// 自定义错误码 六位数字字符串 etc "100000"
'ts' => '',// 10位整形 时间戳
'dateStr' => '',// 日期 2018-06-28 21:24:09
'app' => '',// 应用名称
'serverIp' => '',// 服务器ip
'fileName' => '',// 文件名
'lineNo' => '',// 行数
'method' => '',// 函数名
'apiUrl' => '',// 请求地址
'unique' => '',// 唯一追踪值
'request' => '',// 请求原数据
'response' => '',// 响应原数据
'useTime' => '',// 耗时ms
];
/**
* 自动注册
* @return [type] [description]
*/
static function auto()
{
if (defined('APP_PATH')) {
self::register();
self::set();
} else {
self::$handler = array_map(function($v){
return [];
}, self::$handler);
}
}
/**
* 注册致命错误
* @return [type] [description]
*/
static function register()
{
register_shutdown_function('LogReport::fatalError');
}
/**
* 设置处理方法
*/
static function set()
{
set_error_handler('LogReport::appError');
set_exception_handler('LogReport::exception');
}
/**
* 记录耗时ms
* @param boolean $end true返回耗时 false记录起始记录值
*/
static function LogTime($end = false)
{
if (!$end) {
$time = true;
self::$logtime = microtime(true);
} else {
$time = (microtime(true) - self::$logtime) * 1000;
self::$logtime = null;
}
return $time;
}
/**
* 错误数据格式
* @param string|array $e 错误内容|'message','file','line','code','method',~~
* @param string $file 错误文件
* @param string $line 错误行数
* @param string $code 错误码
* @param string $method 错误函数
* @param string $ip IP
* @param string $unique 追踪唯一值
* @param string $apiUrl 请求地址
* @param string $request 请求值
* @param string $response 响应值
* @param string $useTime 耗时ms
* @return [type] [description]
*/
static function anlyError($e, $file = null, $line = null, $code = null, $method = null, $ip = null, $unique = null,
$apiUrl = null, $request = null, $response = null, $useTime = null)
{
$remote_ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
$default_usetime = !is_null(self::$logtime) ? self::LogTime(true) : '';
$default_unique = isset($_REQUEST['unique']) ? $_REQUEST['unique'] : md5(microtime().rand());
if (!is_array($e)) {
$e = [
'message' => $e,
'file' => $file,
'line' => $line,
'code' => $code,
'method' => $method,
'apiUrl' => $apiUrl,
'request' => $request,
'response' => $response,
'useTime' => !is_null($useTime) ? $useTime : $default_usetime,
'ip' => !is_null($ip) ? $ip : $remote_ip,
'unique' => !is_null($unique) ? $unique : $default_unique,
];
}
$app_name = !empty(self::$app_name) ? self::$app_name : REPORT_APP_NAME;
$data = self::$data;
$data['msg'] = !empty($e['message']) ? $e['message'] : '';
$data['msgCode'] = isset($e['code']) && !empty($e['code']) ? $e['code'] : '';//str_pad($e['code'], 6, '0', STR_PAD_LEFT);
$data['ts'] = time();
$data['dateStr'] = date('Y-m-d H:i:s');
$data['app'] = $app_name.self::$suffix;
$data['serverIp'] = isset($e['ip']) && !empty($e['ip']) ? $e['ip'] : $remote_ip;
$data['fileName'] = isset($e['file']) && !empty($e['file']) ? $e['file'] : '';
$data['lineNo'] = isset($e['line']) && !empty($e['line']) ? $e['line'] : '';
$data['method'] = isset($e['method']) && !empty($e['method']) ? $e['method'] : '';
$data['unique'] = isset($e['unique']) && !empty($e['unique']) ? $e['unique'] : $default_unique;
$data['apiUrl'] = isset($e['apiUrl']) && !empty($e['apiUrl']) ? $e['apiUrl'] : '';
$data['request'] = isset($e['request']) && !empty($e['request']) ? $e['request'] : '';
$data['response'] = isset($e['response']) && !empty($e['response']) ? $e['response'] : '';
$data['useTime'] = isset($e['useTime']) && !empty($e['useTime']) ? $e['useTime'] : $default_usetime;
return $data;
}
/**
* 致命错误处理
* @return [type] [description]
*/
static function fatalError()
{
if ($e = error_get_last()) {
switch ($e['type']) {
case E_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
ob_end_clean();
self::write(self::anlyError($e));
break;
}
}
// exit();
}
/**
* 一般错误处理
* @param [type] $errno [description]
* @param [type] $errstr [description]
* @param [type] $errfile [description]
* @param [type] $errline [description]
* @return [type] [description]
*/
static function appError($errno, $errstr, $errfile, $errline)
{
switch ($errno) {
case E_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
self::write(self::anlyError($errstr , $errfile, $errline));
break;
}
if (!empty(self::$handler['finally_error'])) {
call_user_func(self::$handler['finally_error'], $errno, $errstr, $errfile, $errline);
}
}
/**
* 异常处理
* @return [type] [description]
*/
static function exception($e)
{
self::write(self::anlyError($e->getMessage() , $e->getFile(), $e->getLine()));
if (!empty(self::$handler['finally_except'])) {
call_user_func(self::$handler['finally_except'], $e);
}
}
/**
* 日志记录
* @param string $log 日志内容
* @return [type] [description]
*/
static function write($log)
{
if (is_array($log)) {
$log = json_encode($log);
}
if (empty($log)) {
return false;
}
$report_log_path = !empty(self::$log_path) ? self::$log_path : REPORT_LOG_PATH;
// 自动创建日志目录
if (!is_dir($report_log_path)) {
mkdir($report_log_path, 0755, true);
}
if (in_array(intval(date('H')), explode(',', REPORT_CLEAR_TIME))) { //9-11点触发清空旧数据条件
$dir = scandir($report_log_path);
$clear_day = (int)date_sub(date_create(date('Ymd')), date_interval_create_from_date_string(REPORT_CLEAR_DAY_DIFF. ' days'))->format('Ymd');
if (!empty($dir)) {
array_walk($dir, function($file) use ($clear_day){
$file_arr = explode('-', strchr($file, '.', true), 2);
if ($file_arr[0] != '' && $file_arr[0] <= $clear_day) {
@unlink($report_log_path.$file);
}
});
}
}
$name = date('Ymd');
$filename = $report_log_path.$name.'.log';
//检测日志文件大小,超过配置大小则备份日志文件重新生成
if (is_file($filename) && floor(LOG_FILE_SIZE) <= filesize($filename)) {
rename($filename, dirname($filename) . '/' . $name. '-' . time() . '.log');
}
$log .= PHP_EOL;
return file_put_contents($filename, $log, FILE_APPEND);
}
}
<?php
namespace Common\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
class RedisModel extends Model
{
const WRITE_CONNECT_METHOD = ['set', 'del', 'rpush','lpush', 'expire', 'hset', 'hmset', 'hdel','hsetnx','hincrby'];
const WANRING_LEVEL = 1;
const INGORE_LEVEL = 0;
private $read = [];
private $write = [];
private $level = self::WANRING_LEVEL;
public function __construct($level = self::WANRING_LEVEL, $ConnectWrite = 'default', $ConnectRead = 'read')
{
parent::__construct();
$this->level = $level;
$this->read = Redis::connection($ConnectRead);
$this->write = Redis::connection($ConnectWrite);
}
public function __call($method, $args)
{
$cls = &$this;
$tmp = function($method, $args) use ($cls) {
if (strpos($method, 'pipeline_')) {//使用管道
$method = substr($method, 9);
if (in_array($method, $cls::WRITE_CONNECT_METHOD)) {
return $cls->write->pipeline(function ($pipe) use ($args) {
foreach ($args as $arg) {
$pipe->$method(...$arg);
}
});
} else {
try {
return $cls->read->pipeline(function ($pipe) use ($args) {
foreach ($args as $arg) {
$pipe->$method(...$arg);
}
});
} catch (ConnectionException $e) {
return $cls->write->pipeline(function ($pipe) use ($args) {
foreach ($args as $arg) {
$pipe->$method(...$arg);
}
});
}
}
} else {
if (in_array($method, $cls::WRITE_CONNECT_METHOD)) {
return $cls->write->$method(...$args);
} else {
try {
return $cls->read->$method(...$args);
} catch (ConnectionException $e) {
return $cls->write->$method(...$args);
}
}
}
};
if ($this->level == self::WANRING_LEVEL) {//默认告警级别,抛出异常
if (strpos($method, 'catch_') === 0) {
$method = substr($method, 6);
try {
return $tmp($method, $args);
} catch (\Exception $e) {
return null;
}
} else {
return $tmp($method, $args);
}
} else {
try {
return $tmp($method, $args);
} catch (\Exception $e) {
return null;
}
}
}
//管道
public function pipeline_to_hset($data){
return $this->write->pipeline(function ($pipe) use ($data) {
foreach ($data['data'] as $k => $v) {
$pipe->hset($data['key'],$k,$v);
}
});
}
}
<?php
namespace Rpc\Msg;
/**
* Autogenerated by Thrift Compiler (0.11.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
use Thrift\Base\TBase;
use Thrift\Type\TType;
use Thrift\Type\TMessageType;
use Thrift\Exception\TException;
use Thrift\Exception\TProtocolException;
use Thrift\Protocol\TProtocol;
use Thrift\Protocol\TBinaryProtocolAccelerated;
use Thrift\Exception\TApplicationException;
interface MessageIf {
/**
* @param string $str
* @return string
*/
public function MessageApiAction($str);
}
class MessageClient implements \Rpc\Msg\MessageIf {
protected $input_ = null;
protected $output_ = null;
protected $seqid_ = 0;
public function __construct($input, $output=null) {
$this->input_ = $input;
$this->output_ = $output ? $output : $input;
}
public function MessageApiAction($str)
{
$this->send_MessageApiAction($str);
return $this->recv_MessageApiAction();
}
public function send_MessageApiAction($str)
{
$args = new \Rpc\Msg\Message_MessageApiAction_args();
$args->str = $str;
$bin_accel = ($this->output_ instanceof TBinaryProtocolAccelerated) && function_exists('thrift_protocol_write_binary');
if ($bin_accel)
{
thrift_protocol_write_binary($this->output_, 'MessageApiAction', TMessageType::CALL, $args, $this->seqid_, $this->output_->isStrictWrite());
}
else
{
$this->output_->writeMessageBegin('MessageApiAction', TMessageType::CALL, $this->seqid_);
$args->write($this->output_);
$this->output_->writeMessageEnd();
$this->output_->getTransport()->flush();
}
}
public function recv_MessageApiAction()
{
$bin_accel = ($this->input_ instanceof TBinaryProtocolAccelerated) && function_exists('thrift_protocol_read_binary');
if ($bin_accel) $result = thrift_protocol_read_binary($this->input_, '\Rpc\Msg\Message_MessageApiAction_result', $this->input_->isStrictRead());
else
{
$rseqid = 0;
$fname = null;
$mtype = 0;
$this->input_->readMessageBegin($fname, $mtype, $rseqid);
if ($mtype == TMessageType::EXCEPTION) {
$x = new TApplicationException();
$x->read($this->input_);
$this->input_->readMessageEnd();
throw $x;
}
$result = new \Rpc\Msg\Message_MessageApiAction_result();
$result->read($this->input_);
$this->input_->readMessageEnd();
}
if ($result->success !== null) {
return $result->success;
}
throw new \Exception("MessageApiAction failed: unknown result");
}
}
// HELPER FUNCTIONS AND STRUCTURES
class Message_MessageApiAction_args {
static $isValidate = false;
static $_TSPEC = array(
1 => array(
'var' => 'str',
'isRequired' => false,
'type' => TType::STRING,
),
);
/**
* @var string
*/
public $str = null;
public function __construct($vals=null) {
if (is_array($vals)) {
if (isset($vals['str'])) {
$this->str = $vals['str'];
}
}
}
public function getName() {
return 'Message_MessageApiAction_args';
}
public function read($input)
{
$xfer = 0;
$fname = null;
$ftype = 0;
$fid = 0;
$xfer += $input->readStructBegin($fname);
while (true)
{
$xfer += $input->readFieldBegin($fname, $ftype, $fid);
if ($ftype == TType::STOP) {
break;
}
switch ($fid)
{
case 1:
if ($ftype == TType::STRING) {
$xfer += $input->readString($this->str);
} else {
$xfer += $input->skip($ftype);
}
break;
default:
$xfer += $input->skip($ftype);
break;
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
public function write($output) {
$xfer = 0;
$xfer += $output->writeStructBegin('Message_MessageApiAction_args');
if ($this->str !== null) {
$xfer += $output->writeFieldBegin('str', TType::STRING, 1);
$xfer += $output->writeString($this->str);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
}
class Message_MessageApiAction_result {
static $isValidate = false;
static $_TSPEC = array(
0 => array(
'var' => 'success',
'isRequired' => false,
'type' => TType::STRING,
),
);
/**
* @var string
*/
public $success = null;
public function __construct($vals=null) {
if (is_array($vals)) {
if (isset($vals['success'])) {
$this->success = $vals['success'];
}
}
}
public function getName() {
return 'Message_MessageApiAction_result';
}
public function read($input)
{
$xfer = 0;
$fname = null;
$ftype = 0;
$fid = 0;
$xfer += $input->readStructBegin($fname);
while (true)
{
$xfer += $input->readFieldBegin($fname, $ftype, $fid);
if ($ftype == TType::STOP) {
break;
}
switch ($fid)
{
case 0:
if ($ftype == TType::STRING) {
$xfer += $input->readString($this->success);
} else {
$xfer += $input->skip($ftype);
}
break;
default:
$xfer += $input->skip($ftype);
break;
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
public function write($output) {
$xfer = 0;
$xfer += $output->writeStructBegin('Message_MessageApiAction_result');
if ($this->success !== null) {
$xfer += $output->writeFieldBegin('success', TType::STRING, 0);
$xfer += $output->writeString($this->success);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
}
<?php
namespace Rpc\Msg;
/**
* Autogenerated by Thrift Compiler (0.11.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
use Thrift\Base\TBase;
use Thrift\Type\TType;
use Thrift\Type\TMessageType;
use Thrift\Exception\TException;
use Thrift\Exception\TProtocolException;
use Thrift\Protocol\TProtocol;
use Thrift\Protocol\TBinaryProtocolAccelerated;
use Thrift\Exception\TApplicationException;
interface SendMsgIf {
/**
* @param string $str
* @return string
*/
public function sendMsg($str);
}
class SendMsgClient implements \Rpc\Msg\SendMsgIf {
protected $input_ = null;
protected $output_ = null;
protected $seqid_ = 0;
public function __construct($input, $output=null) {
$this->input_ = $input;
$this->output_ = $output ? $output : $input;
}
public function sendMsg($str)
{
$this->send_sendMsg($str);
return $this->recv_sendMsg();
}
public function send_sendMsg($str)
{
$args = new \Rpc\Msg\SendMsg_sendMsg_args();
$args->str = $str;
$bin_accel = ($this->output_ instanceof TBinaryProtocolAccelerated) && function_exists('thrift_protocol_write_binary');
if ($bin_accel)
{
thrift_protocol_write_binary($this->output_, 'sendMsg', TMessageType::CALL, $args, $this->seqid_, $this->output_->isStrictWrite());
}
else
{
$this->output_->writeMessageBegin('sendMsg', TMessageType::CALL, $this->seqid_);
$args->write($this->output_);
$this->output_->writeMessageEnd();
$this->output_->getTransport()->flush();
}
}
public function recv_sendMsg()
{
$bin_accel = ($this->input_ instanceof TBinaryProtocolAccelerated) && function_exists('thrift_protocol_read_binary');
if ($bin_accel) $result = thrift_protocol_read_binary($this->input_, '\Rpc\Msg\SendMsg_sendMsg_result', $this->input_->isStrictRead());
else
{
$rseqid = 0;
$fname = null;
$mtype = 0;
$this->input_->readMessageBegin($fname, $mtype, $rseqid);
if ($mtype == TMessageType::EXCEPTION) {
$x = new TApplicationException();
$x->read($this->input_);
$this->input_->readMessageEnd();
throw $x;
}
$result = new \Rpc\Msg\SendMsg_sendMsg_result();
$result->read($this->input_);
$this->input_->readMessageEnd();
}
if ($result->success !== null) {
return $result->success;
}
throw new \Exception("sendMsg failed: unknown result");
}
}
// HELPER FUNCTIONS AND STRUCTURES
class SendMsg_sendMsg_args {
static $isValidate = false;
static $_TSPEC = array(
1 => array(
'var' => 'str',
'isRequired' => false,
'type' => TType::STRING,
),
);
/**
* @var string
*/
public $str = null;
public function __construct($vals=null) {
if (is_array($vals)) {
if (isset($vals['str'])) {
$this->str = $vals['str'];
}
}
}
public function getName() {
return 'SendMsg_sendMsg_args';
}
public function read($input)
{
$xfer = 0;
$fname = null;
$ftype = 0;
$fid = 0;
$xfer += $input->readStructBegin($fname);
while (true)
{
$xfer += $input->readFieldBegin($fname, $ftype, $fid);
if ($ftype == TType::STOP) {
break;
}
switch ($fid)
{
case 1:
if ($ftype == TType::STRING) {
$xfer += $input->readString($this->str);
} else {
$xfer += $input->skip($ftype);
}
break;
default:
$xfer += $input->skip($ftype);
break;
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
public function write($output) {
$xfer = 0;
$xfer += $output->writeStructBegin('SendMsg_sendMsg_args');
if ($this->str !== null) {
$xfer += $output->writeFieldBegin('str', TType::STRING, 1);
$xfer += $output->writeString($this->str);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
}
class SendMsg_sendMsg_result {
static $isValidate = false;
static $_TSPEC = array(
0 => array(
'var' => 'success',
'isRequired' => false,
'type' => TType::STRING,
),
);
/**
* @var string
*/
public $success = null;
public function __construct($vals=null) {
if (is_array($vals)) {
if (isset($vals['success'])) {
$this->success = $vals['success'];
}
}
}
public function getName() {
return 'SendMsg_sendMsg_result';
}
public function read($input)
{
$xfer = 0;
$fname = null;
$ftype = 0;
$fid = 0;
$xfer += $input->readStructBegin($fname);
while (true)
{
$xfer += $input->readFieldBegin($fname, $ftype, $fid);
if ($ftype == TType::STOP) {
break;
}
switch ($fid)
{
case 0:
if ($ftype == TType::STRING) {
$xfer += $input->readString($this->success);
} else {
$xfer += $input->skip($ftype);
}
break;
default:
$xfer += $input->skip($ftype);
break;
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
public function write($output) {
$xfer = 0;
$xfer += $output->writeStructBegin('SendMsg_sendMsg_result');
if ($this->success !== null) {
$xfer += $output->writeFieldBegin('success', TType::STRING, 0);
$xfer += $output->writeString($this->success);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
}
<?php
namespace Rpc\Msg;
/**
* Autogenerated by Thrift Compiler (0.11.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
use Thrift\Base\TBase;
use Thrift\Type\TType;
use Thrift\Type\TMessageType;
use Thrift\Exception\TException;
use Thrift\Exception\TProtocolException;
use Thrift\Protocol\TProtocol;
use Thrift\Protocol\TBinaryProtocolAccelerated;
use Thrift\Exception\TApplicationException;
<?php
namespace Rpc;
use Thrift\Exception\TException;
use Thrift\Protocol\TBinaryProtocol;
use Thrift\Transport\TBufferedTransport;
use Thrift\Transport\THttpClient;
use Thrift\Transport\TPhpStream;
use Thrift\TMultiplexedProcessor;
use Thrift\Protocol\TMultiplexedProtocol;
use Thrift\Factory\TBinaryProtocolFactory;
use Thrift\Factory\TTransportFactory;
use Thrift\Server\TServerSocket;
use Thrift\Server\TSimpleServer;
use Thrift\Server\TForkingServer;
use Thrift\Transport\TSocket;
class MsgRpcClient {
public function sendMsg($data){
try {
ini_set('memory_limit', '1024M');
$socket = new TSocket('192.168.2.245', '9988');
$socket->setRecvTimeout(50000);
$socket->setDebug(true);
$transport = new TBufferedTransport($socket, 1024, 1024);
$protocol = new TBinaryProtocol($transport);
$client = new \Rpc\Msg\SendMsgClient(new TMultiplexedProtocol($protocol, "sendMsg"));
$transport->open();
$result = $client->sendMsg(json_encode($data));
print_r($result);
$transport->close();
} catch (TException $tx) {
print_r($tx->getMessage());
}
}
}
\ No newline at end of file
{
"name": "laravel/lumen",
"description": "The Laravel Lumen Framework.",
"keywords": ["framework", "laravel", "lumen"],
"license": "MIT",
"type": "project",
"require": {
"php": ">=5.6.4",
"laravel/lumen-framework": "5.5.*",
"vlucas/phpdotenv": "~2.2",
"lumening/lumen-hprose": "^0.2.0@beta",
"maatwebsite/excel" :"~2.1.0",
"predis/predis": "^1.1",
"illuminate/redis": "^5.5",
"aliyuncs/oss-sdk-php": "^2.3"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"phpunit/phpunit": "~6.0",
"mockery/mockery": "~0.9",
"composer/composer": "^1.8"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Common\\": "common/"
},
"files": [
"common/function.php",
"common/LogReport.php"
]
},
"autoload-dev": {
"classmap": [
"tests/",
"database/"
]
},
"scripts": {
"post-root-package-install": [
"php -r \"copy('.env.example', '.env');\""
]
},
"minimum-stability": "dev",
"prefer-stable": true,
"optimize-autoloader": true
}
This diff could not be displayed because it is too large.
<?php
return [
'SUPER_AUTH_KEY' => 'fh6y5t4rr351d2c3bryi',
'OSS_URL' => 'http://img.icsales.com/',
'AccessKeyId' => 'LTAIoG57wX1XfyCn',
'AccessKeySecret' => 'ZurpnMpFAq3ap7MhduGTgJq4GxglCE',
'EndPoint' => 'http://oss-cn-shenzhen.aliyuncs.com',
'Bucket' => 'icsales-files-2019',
// 内部、外部上传文件数量限制
'InternalNum' => 10,
'ExternalNum' => 5,
];
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: ICHUNT
* Date: 2019-06-27
* Time: 10:39
*/
return [
'upload_goods_status'=>[
1 => '待处理',
2 => '处理中',
3 => '处理成功',
4 => '处理失败'
]
];
\ No newline at end of file
<?php
return [
/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/
'fetch' => PDO::FETCH_CLASS,
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'testing' => [
'driver' => 'sqlite',
'database' => ':memory:',
],
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', base_path('database/database.sqlite')),
'prefix' => env('DB_PREFIX', ''),
],
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', 3306),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'collation' => env('DB_COLLATION', 'utf8_unicode_ci'),
'prefix' => env('DB_PREFIX', ''),
'timezone' => env('DB_TIMEZONE', '+00:00'),
'strict' => env('DB_STRICT_MODE', false),
],
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', 5432),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => env('DB_PREFIX', ''),
'schema' => env('DB_SCHEMA', 'public'),
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => env('DB_PREFIX', ''),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'cluster' => env('REDIS_CLUSTER', false),
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0
],
'read' =>[
'host' => env('REDIS_READ_HOST', ''),
'password' => env('REDIS_READ_PASSWORD', null),
'port' => env('REDIS_READ_PORT', 6379),
'database' => 0
]
],
];
<?php
/**
* Created by PhpStorm.
* User: ICHUNT
* Date: 2019-06-20
* Time: 17:55
*/
return [
'cn' => [
103001 => '非法操作',
103002 => 'Hprose请求失败',
103003 => '登录失败',
// oss 错误码
103200 => '上传成功',
103201 => '参数缺失,请检查传递的参数',
103202 => '内部免验证不通过',
103203 => '上传文件数量超出限制',
103204 => '暂不支持此文件类型上传',
103205 => '请求方法不被允许',
103206 => '文件过大,最大限制为2M,请重新上传',
103207 => '文件过大,最大限制为20M,请重新上传',
103208 => '文件过大,最大限制为50M,请重新上传',
103209 => '文件过大,最大限制为30M,请重新上传',
103210 => '没匹配到文件类型',
103211 => '上传失败,请重新上传',
],
'us' => [
103001 => 'Illegal operation',
103002 => 'Hprose request failed, please check it',
103003 => 'Login failed',
// oss 错误码
103200 => 'Upload success',
103201 => 'Parameter missing, please check the passed parameters',
103202 => 'Internal certification-free fails',
103203 => 'The number of uploaded files exceeds the limit',
103204 => 'This file type upload is not supported for the time being',
103205 => 'Request method is not allowed',
103206 => 'The File is too large, the maximum limit is 2M, please re-upload',
103207 => 'The File is too large, the maximum limit is 20M, please re-upload',
103208 => 'The File is too large, the maximum limit is 50M, please re-upload',
103209 => 'The File is too large, the maximum limit is 30M, please re-upload',
103210 => 'Not matched to file type',
103211 => 'Upload failed, please try again',
],
];
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: ICHUNT
* Date: 2019-06-18
* Time: 11:46
*/
return [
'SystemCode'=>env('SYSTEM_CODE','00'),//系统编码,需要在tapd维护,请勿占用已使用的编码
'SystemName'=>env('SYSTEM_NAME','这家伙没设置系统'),//系统名称
'GoodsInfoUrl' => env('GoodsInfoUrl',''),
'ES_URL' => env('ES_URL'),
'authapi' => env('authapi'),
'allow_origin'=>[
'http://home.icsales.cc',
'http://search.icsales.cc',
'http://loss.liexin.net',
],
'language'=>[
''
],
'upload_goods_num'=>200,
'upload_goods_title'=>[
'*型号','*品牌','封装','库存','单价','币种(人民币/美金)','*货期(现货/货期)'
],
'UploadKey' => 'fh6y5t4rr351d2c3bryi',//api的秘钥
'UploadUrl' => 'http://api.liexin.com/oss/upload',//上传OSS地址
];
\ No newline at end of file
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->email,
];
});
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// $this->call('UsersTableSeeder');
}
}
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="bootstrap/app.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false">
<testsuites>
<testsuite name="Application Test Suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
</php>
</phpunit>
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
<?xml version="1.0" encoding="UTF-8"?>
<cross-domain-policy>
<allow-access-from domain="*.icsales.cc" />
</cross-domain-policy>
\ No newline at end of file
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| First we need to get an application instance. This creates an instance
| of the application / container and bootstraps the application so it
| is ready to receive HTTP / Console requests from the environment.
|
*/
$app = require __DIR__.'/../bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/
$app->run();
# Lumen PHP Framework
[![Build Status](https://travis-ci.org/laravel/lumen-framework.svg)](https://travis-ci.org/laravel/lumen-framework)
[![Total Downloads](https://poser.pugx.org/laravel/lumen-framework/d/total.svg)](https://packagist.org/packages/laravel/lumen-framework)
[![Latest Stable Version](https://poser.pugx.org/laravel/lumen-framework/v/stable.svg)](https://packagist.org/packages/laravel/lumen-framework)
[![Latest Unstable Version](https://poser.pugx.org/laravel/lumen-framework/v/unstable.svg)](https://packagist.org/packages/laravel/lumen-framework)
[![License](https://poser.pugx.org/laravel/lumen-framework/license.svg)](https://packagist.org/packages/laravel/lumen-framework)
Laravel Lumen is a stunningly fast PHP micro-framework for building web applications with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Lumen attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as routing, database abstraction, queueing, and caching.
## Official Documentation
Documentation for the framework can be found on the [Lumen website](http://lumen.laravel.com/docs).
## Security Vulnerabilities
If you discover a security vulnerability within Lumen, please send an e-mail to Taylor Otwell at taylor@laravel.com. All security vulnerabilities will be promptly addressed.
## License
The Lumen framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
$router->get('/', function () use ($router) {
return $router->app->version();
});
$router->group(['middleware' => ['web','login']], function ()use($router) {
$router->get('/goods/add', 'ApiController@AddGoods');
$router->get('/goods/info', 'ApiController@GoodsInfo');
$router->get('/goods/save', 'ApiController@SaveGoods');
$router->get('/goods/status', 'ApiController@GoodsStatus');
$router->get('/goods/count', 'ApiController@MysqlGoodsCount');
$router->post('/goods/upload', 'ApiController@UploadGoods');
$router->options('/goods/upload', 'ApiController@UploadGoods');//前端插件需要这个请求
$router->get('/goods/upload/list', 'ApiController@UploadGoodsList');
});
$router->group(['middleware' => 'web'], function ()use($router) {
$router->post('/oss/upload', 'OssController@upload');
$router->get('/goods/search', 'ApiController@GoodsInfo');
});
//$router->get('crossdomain.xml', 'ApiController@crossdomain');
\ No newline at end of file
No preview for this file type
*商品型号,*制造商,*库存数量,"*最小起订量
(MOQ)",标准包装量(MPQ),封装,批次,简短描述,*阶梯数量1,*国内含税价1(¥),*香港交货价1($),阶梯数量2,国内含税价2(¥),香港交货价2($),阶梯数量3,国内含税价3(¥),香港交货价3($),阶梯数量4,国内含税价4(¥),香港交货价4($),阶梯数量5,国内含税价5(¥),香港交货价5($),阶梯数量6,国内含税价6(¥),香港交货价6($),阶梯数量7,国内含税价7(¥),香港交货价7($),阶梯数量8,国内含税价8(¥),香港交货价8($),阶梯数量9,国内含税价9(¥),香港交货价9($)
lm358,ADI,1000,10,,200,12+,这就是简短描述,10,100,10,,,,,,,,,,,,,,,,,,,,,,,,
No preview for this file type
No preview for this file type
<?php
use Laravel\Lumen\Testing\DatabaseMigrations;
use Laravel\Lumen\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testExample()
{
$this->get('/');
$this->assertEquals(
$this->app->version(), $this->response->getContent()
);
}
}
<?php
abstract class TestCase extends Laravel\Lumen\Testing\TestCase
{
/**
* Creates the application.
*
* @return \Laravel\Lumen\Application
*/
public function createApplication()
{
return require __DIR__.'/../bootstrap/app.php';
}
}
coverage_clover: coverage.xml
json_path: coverage.json
vendor
composer.lock
doc
output
.idea
.buildpath
.project
.settings
language: php
php:
- 7.1
- 7.0
- 5.6
- 5.5
- 5.4
install:
- composer self-update
- composer install --no-interaction
script:
- php vendor/bin/phpunit
after_success:
- php vendor/bin/coveralls -v
env:
global:
- secure: SzmQ854lQmhV6ZkAG7lQNTY3CkazrXnDSb6VMwPU/sdaLGxPO159AW3fJS5d0sO/XN1P8x5WNkoA4i9soDlLBRibEEISNUM/2EMnpszsRymZ9o97PrS2IgORXTUL/OF+rpATzyNVB2p+2l9hBLiGf17exMSA5iOeY7W6E+VKPGi8TFykgbGUnLKU0h1hV3rzmtfGjOXcSpvYU/hxeZD/J/+6m5Gic9b/pNS+AbfTj7Y7Ru9tNsnyUP29V/vtEYtpQir3ZxQiSiUv9idybgGnJBOMYydJofb/mpFYHhYLSWqtMKGNLpeawmqs4z8S1Tvx5U5uzW5+h/mpzhvBaFlWGpm8t89BQxun5LVX5NiYCrV7TqaLitGp1cSpMjMDnrnSTNzk1exVz+rWZZcWS7yB9ULYA681GA8StXWk167qB7Y30iK1dFK3+2mDN2cEY+qLs8+bupDowQ4eOM+eqfhxX8F8+ouKcKomETsjiIwL+CUsIe6wjvnYFWb1YlRhbsI75bblHApflohnt6gVSJ78ZPqID+u2oUMjmIWXLTnRR2Y2tgEW8uqHeIoQ8BBntLdQDmv0BO4FpnGQIwrUUwQYeNzEM0DOr3hWZhyDR6Xvl+9H0l52xjANaSqpuTZfC3zmeFTG7kIjydvxNePRrony6XAawL9BvI7aKWuVF6YVjPM=
- secure: nEhsU8aUQqsAJeuger+boh51oTpeo4YNG7vUWbKxdwVDIrcLb+l7r7RvTlxU7mt8IZTWwicgri18mh+Wi04BwX4ulBA1SCs8jPbL51KEo5izoDGGtLSd2fuPHdslYSrwagrvq90EPnDT/7fHWn/TAoT+rueZzjNyCu5IGSgL3GnXaUThsJ82NMePL2YRdP4Q1qmtZPRFBOkOQ6F0heuV8fw8sLyTO3txaCQum9YneGxrWxOl/E8zB0qtlnPwLE8ogaHZMQh2/jThmTbI5UqwRTxV4f0qoD5eJYH+j0fslsSAjsg/HPnSuVcnccK3zSU+s2sV4dPCcISzECJvZEObwipfxOGhdqt5gMcxHhn8qVsbT97iIh106pG/BJCDgQd2EeVW8WfCi6cCuCKIMipvVkMypkmjQHWU1XaqPzILl7g5diW9Ctp2C4Akq5dYdrdu8IrnVK1ShtkQVaWU+S/Bht8VU5gYP7olPW/GdTz7sceU1NOIC4NPXqmWKbfavR98U5dkHMLMvzABYL1Q87h+KhPD1c14NUyw3YENUW7REiF/X5lERRm5H0kJ/1JqAa+AgeHQEGmPVuZV2s/na4b0S1479QRVmSM/6ZzXQpU+Y8jCRfETpUFA4S331369kirHgCqDlxyIntuEKrzivD02/O+5C3eJ0WHRz6QsN2/R4qg=
- secure: ZTvzNXEZP4efl+a/3VGMmdabfUQp83v5/lecMns039Ro7UuZYPdtbPtpPnpjaTI6Htd22A4Rva5BU/3JCQJAyQvpbKNn5sGou2SmfQu3o0SyhggSB7gWjYAf707aW1j4bHYfP8IjDS5NjuVk3AqXeNSUuLRUXRmwSOB0lSYiRhiTJY+pUdBl382Hx4NbhIU/gmOzRoJCs7coTip8IURXYEHPi5dnDWluajxI+TgNXFccSgEleeQDJajYgXmpLb2EhSj8piipOnVgaCEE5bh5fbp32024Qq38SGHKcbfnwj2IInpZpZESJknRKoqAlFjdOJhork82dBcvAr5JxCBZKx5IuwXcTjxkQ6tRtBeqhPLPFuX3MQ8WrtU+wniPM0RCH/VoFkUKO7JGQDwmoi2AKago4PsuDs4P6Y6CeuOVpcso731GwwMNhIJcyrJJivXprQNEGsEw+9wLjU1qNYs6IIA3S/gPzFrNbdX5Wf8vxt0vLpgYvBNtPnLMejMtknuyfVzf5iKuVVoGPDTEz+ajs06+jfoPfm/4sLTaLghuVH7Adm74OpF769JQNnQYKwJuu4bNlcbLJChulCEMBOx7myqo/9O6RCTuqzHaGmVWNot4RGqRFHgJGl/JJf0WpAVitbhbRH3kGoyKb6jFM74CJbPsE7OORlJLDC3cdD3C8Pk=
- secure: Qr5NR4CVzBKCQgRgMH0x772TPJ1+brx3UCvtRNu8fi4j3p8bz+HDMjBaBDSFmEB09nunLI55/8mj88/5GXmnpFs8+CPTkcW+QZOcxg3cxpI4SNmxoB12/ZawlFHAqSUaRRE7RUWVkY3KL8tIGjEZcFyUBQ1DVNX3OMpiKs3NLtHa7oUIknyBxdSokm4kpLhSXYe7WmO0vhuZbMZE0S1EISToiBS6AdhGUEbTLJ/vNsIDY07fu6+Vh3HxVbyUFPqUZGlkZpQ+2xMJ3kiqPBMrXtRF/IhhPjORDil6Ns9SQ8/AAlaCddvYvRaT4Pjv2/aX+t3l28qI1qmryPtWXpce5UXecWGYqdRpSJc6Y/pEt4m4FeeGoEFWnSPGIs7FRmeiis8q2rojGZ18i4vI/k4iHmqEBnTlMp3SWnRb9L1adJ8ZAWln8aC88gkQXm67w7+1CxLycerbYj9H1ugqHENuHcxv4uHUcZgEENX3EWatu8i9+K2IUuU/2zcmpu7qtsziYcoyW8DOOmYpJfXGMLtmF9+pqp/Tp6i0tltFSEfmY3N8o7xvv3enLvFHsjL+3ElFdd1blUPSrvZJHgA9M3lJ+QF1RJZCpJqgPlQ0XOZK1Bf4P46zpEj01wKaK4JQrkLPRXhbBOuIJn5O6WlFJyPX4+SaBfwTzb4AvM4aUg2TgTg=
- secure: Inw5ftA8fxvhMHRZwoZzATxn4WICJsCq7ZX4y2gI+b/8u0JQIsbLgY9WTYV+XdSxOoNwuVa1oUxEWI0aDORtXKC3XaIXXKrwndag0zxS77JEYwWvQsjM7BhEbF7MF7MYk8rRXpn6mbfGAT/NfqEOx91RCY8UKeMzD0oPkpkBnJ9Ekuod6JBBq+7j3v4mYUItA8pxvw7b4Pdd4z2xzjgOwNhJYMOCpts50DWZI+WXj0HvTYaMXe5mJJtORK5lsr0a9cbsBqAzE6l+3zGI8XkgHn130ux5XH3DE7hZBeti3ZNaO3d2Vv+496/1EObG0rSFk+z3dmNKqjMz4nh3bYIkdLMegwmgCWs2mvQhkwYhzmnPRHVSERrgZjSWnuKn2PKnBar6tui9KaLNgpo2j3jWpwMLJ3bGAfE5JtMppxAxNqj/q+YB2UZo7Mn7EDjkTDjgxCuazTJwWqH7xxCOykWPABBI17P3JaOXQJEK39LavpfSMm3kdmU0ocpUs7FniLuFm6xL71VxY1wHG10yskczEcFHZ3iyIyGM+xum4vbt5y6Yg+zfdExYQsbrxHDDZ3HbHY3tEU0WhM55vrC42NIXRWqXqJ8OAxpl4nivfx96eoBAThiUU9xXtZmh7WRFVYsstoGtxZwfk5+bi+oeVO9kih4xabwbgHgL9BTc1TR1C4U=
# ChangeLog - Aliyun OSS SDK for PHP
## v2.3.0 / 2018-01-05
* 修复:putObject支持创建空文件
* 修复:createBucket支持IA/Archive
* 增加:支持restoreObject
* 增加:支持Symlink功能
* 增加:支持getBucketLocation
* 增加:支持getBucketMeta
* 增加:支持代理服务器Proxy
## v2.2.4 / 2017-04-25
* fix getObject to local file bug
## v2.2.3 / 2017-04-14
* fix md5 check
## v2.2.2 / 2017-01-18
* 解决在php7上运行连接数和内存bug
## v2.2.1 / 2016-12-01
* 禁止http curl自动填充Accept-Encoding
## v2.2.0 / 2016-11-22
* 修复PutObject/CompleteMultipartUpload的返回值问题(#26)
## v2.1.0 / 2016-11-12
* 增加[RTMP](https://help.aliyun.com/document_detail/44297.html)接口
* 增加支持[图片服务](https://help.aliyun.com/document_detail/44686.html)
## v2.0.7 / 2016-06-17
* Support append object
## v2.0.6
* Trim access key id/secret and endpoint
* Refine tests and setup travis CI
## v2.0.5
* 增加Add/Delete/Get BucketCname接口
## v2.0.4
* 增加Put/Get Object Acl接口
## v2.0.3
* 修复Util中的常量定义在低于5.6的PHP版本中报错的问题
## v2.0.2
* 修复multipart上传时无法指定Content-Type的问题
## v2.0.1
* 增加对ListObjects/ListMultipartUploads时特殊字符的处理
* 提供接口获取OssException中的详细信息
## 2015.11.25
* **大版本升级,不再兼容以前接口,新版本对易用性做了很大的改进,建议用户迁移到新版本。**
## 修改内容
* 不再支持PHP 5.2版本
### 新增内容
* 引入命名空间
* 接口命名修正,采用驼峰式命名
* 接口入参修改,把常用参数从Options参数中提出来
* 接口返回结果修改,对返回结果进行处理,用户可以直接得到容易处理的数据结构 
* OssClient的构造函数变更
* 支持CNAME和IP格式的Endpoint地址
* 重新整理sample文件组织结构,使用function组织功能点
* 增加设置连接超时,请求超时的接口
* 去掉Object Group相关的已经过时的接口
* OssException中的message改为英文
### 问题修复
* object名称校验不完备
#The MIT License (MIT)
Copyright (c) ali-sdk and other contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
\ No newline at end of file
# Aliyun OSS SDK for PHP
[![Latest Stable Version](https://poser.pugx.org/aliyuncs/oss-sdk-php/v/stable)](https://packagist.org/packages/aliyuncs/oss-sdk-php)
[![Build Status](https://travis-ci.org/aliyun/aliyun-oss-php-sdk.svg?branch=master)](https://travis-ci.org/aliyun/aliyun-oss-php-sdk)
[![Coverage Status](https://coveralls.io/repos/github/aliyun/aliyun-oss-php-sdk/badge.svg?branch=master)](https://coveralls.io/github/aliyun/aliyun-oss-php-sdk?branch=master)
## [README of English](https://github.com/aliyun/aliyun-oss-php-sdk/blob/master/README.md)
## 概述
阿里云对象存储(Object Storage Service,简称OSS),是阿里云对外提供的海量、安全、低成本、高可靠的云存储服务。用户可以通过调用API,在任何应用、任何时间、任何地点上传和下载数据,也可以通过用户Web控制台对数据进行简单的管理。OSS适合存放任意文件类型,适合各种网站、开发企业及开发者使用。
## 运行环境
- PHP 5.3+
- cURL extension
提示:
- Ubuntu下可以使用apt-get包管理器安装php的cURL扩展 `sudo apt-get install php5-curl`
## 安装方法
1. 如果您通过composer管理您的项目依赖,可以在你的项目根目录运行:
$ composer require aliyuncs/oss-sdk-php
或者在你的`composer.json`中声明对Aliyun OSS SDK for PHP的依赖:
"require": {
"aliyuncs/oss-sdk-php": "~2.0"
}
然后通过`composer install`安装依赖。composer安装完成后,在您的PHP代码中引入依赖即可:
require_once __DIR__ . '/vendor/autoload.php';
2. 您也可以直接下载已经打包好的[phar文件][releases-page],然后在你
的代码中引入这个文件即可:
require_once '/path/to/oss-sdk-php.phar';
3. 下载SDK源码,在您的代码中引入SDK目录下的`autoload.php`文件:
require_once '/path/to/oss-sdk/autoload.php';
## 快速使用
### 常用类
| 类名 | 解释 |
|:------------------|:------------------------------------|
|OSS\OssClient | OSS客户端类,用户通过OssClient的实例调用接口 |
|OSS\Core\OssException | OSS异常类,用户在使用的过程中,只需要注意这个异常|
### OssClient初始化
SDK的OSS操作通过OssClient类完成的,下面代码创建一个OssClient对象:
```php
<?php
$accessKeyId = "<您从OSS获得的AccessKeyId>"; ;
$accessKeySecret = "<您从OSS获得的AccessKeySecret>";
$endpoint = "<您选定的OSS数据中心访问域名,例如oss-cn-hangzhou.aliyuncs.com>";
try {
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
} catch (OssException $e) {
print $e->getMessage();
}
```
### 文件操作
文件(又称对象,Object)是OSS中最基本的数据单元,您可以把它简单地理解为文件,用下面代码可以实现一个Object的上传:
```php
<?php
$bucket = "<您使用的Bucket名字,注意命名规范>";
$object = "<您使用的Object名字,注意命名规范>";
$content = "Hello, OSS!"; // 上传的文件内容
try {
$ossClient->putObject($bucket, $object, $content);
} catch (OssException $e) {
print $e->getMessage();
}
```
### 存储空间操作
存储空间(又称Bucket)是一个用户用来管理所存储Object的存储空间,对于用户来说是一个管理Object的单元,所有的Object都必须隶属于某个Bucket。您可以按照下面的代码新建一个Bucket:
```php
<?php
$bucket = "<您使用的Bucket名字,注意命名规范>";
try {
$ossClient->createBucket($bucket);
} catch (OssException $e) {
print $e->getMessage();
}
```
### 返回结果处理
OssClient提供的接口返回返回数据分为两种:
* Put,Delete类接口,接口返回null,如果没有OssException,即可认为操作成功
* Get,List类接口,接口返回对应的数据,如果没有OssException,即可认为操作成功,举个例子:
```php
<?php
$bucketListInfo = $ossClient->listBuckets();
$bucketList = $bucketListInfo->getBucketList();
foreach($bucketList as $bucket) {
print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreatedate() . "\n");
}
```
上面代码中的$bucketListInfo的数据类型是 `OSS\Model\BucketListInfo`
### 运行Sample程序
1. 修改 `samples/Config.php`, 补充配置信息
2. 执行 `cd samples/ && php RunAll.php`
### 运行单元测试
1. 执行`composer install`下载依赖的库
2. 设置环境变量
export OSS_ACCESS_KEY_ID=access-key-id
export OSS_ACCESS_KEY_SECRET=access-key-secret
export OSS_ENDPOINT=endpoint
export OSS_BUCKET=bucket-name
3. 执行 `php vendor/bin/phpunit`
## License
- MIT
## 联系我们
- [阿里云OSS官方网站](http://oss.aliyun.com)
- [阿里云OSS官方论坛](http://bbs.aliyun.com)
- [阿里云OSS官方文档中心](http://www.aliyun.com/product/oss#Docs)
- 阿里云官方技术支持:[提交工单](https://workorder.console.aliyun.com/#/ticket/createIndex)
[releases-page]: https://github.com/aliyun/aliyun-oss-php-sdk/releases
[phar-composer]: https://github.com/clue/phar-composer
# Alibaba Cloud OSS SDK for PHP
[![Latest Stable Version](https://poser.pugx.org/aliyuncs/oss-sdk-php/v/stable)](https://packagist.org/packages/aliyuncs/oss-sdk-php)
[![Build Status](https://travis-ci.org/aliyun/aliyun-oss-php-sdk.svg?branch=master)](https://travis-ci.org/aliyun/aliyun-oss-php-sdk)
[![Coverage Status](https://coveralls.io/repos/github/aliyun/aliyun-oss-php-sdk/badge.svg?branch=master)](https://coveralls.io/github/aliyun/aliyun-oss-php-sdk?branch=master)
## [README of Chinese](https://github.com/aliyun/aliyun-oss-php-sdk/blob/master/README-CN.md)
## Overview
Alibaba Cloud Object Storage Service (OSS) is a cloud storage service provided by Alibaba Cloud, featuring a massive capacity, security, a low cost, and high reliability. You can upload and download data on any application anytime and anywhere by calling APIs, and perform simple management of data through the web console. The OSS can store any type of files and therefore applies to various websites, development enterprises and developers.
## Run environment
- PHP 5.3+.
- cURL extension.
Tips:
- In Ubuntu, you can use the ***apt-get*** package manager to install the *PHP cURL extension*: `sudo apt-get install php5-curl`.
## Install OSS PHP SDK
- If you use the ***composer*** to manage project dependencies, run the following command in your project's root directory:
composer require aliyuncs/oss-sdk-php
You can also declare the dependency on Alibaba Cloud OSS SDK for PHP in the `composer.json` file.
"require": {
"aliyuncs/oss-sdk-php": "~2.0"
}
Then run `composer install` to install the dependency. After the Composer Dependency Manager is installed, import the dependency in your PHP code:
require_once __DIR__ . '/vendor/autoload.php';
- You can also directly download the packaged [PHAR File][releases-page], and
introduce the file to your code:
require_once '/path/to/oss-sdk-php.phar';
- Download the SDK source code, and introduce the `autoload.php` file under the SDK directory to your code:
require_once '/path/to/oss-sdk/autoload.php';
## Quick use
### Common classes
| Class | Explanation |
|:------------------|:------------------------------------|
|OSS\OSSClient | OSS client class. An OSSClient instance can be used to call the interface. |
|OSS\Core\OSSException |OSS Exception class . You only need to pay attention to this exception when you use the OSSClient. |
### Initialize an OSSClient
The SDK's operations for the OSS are performed through the OSSClient class. The code below creates an OSSClient object:
```php
<?php
$accessKeyId = "<AccessKeyID that you obtain from OSS>";
$accessKeySecret = "<AccessKeySecret that you obtain from OSS>";
$endpoint = "<Domain that you select to access an OSS data center, such as "oss-cn-hangzhou.aliyuncs.com>";
try {
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
} catch (OssException $e) {
print $e->getMessage();
}
```
### Operations on objects
Objects are the most basic data units on the OSS. You can simply consider objects as files. The following code uploads an object:
```php
<?php
$bucket= "<Name of the bucket in use. Pay attention to naming conventions>";
$object = "<Name of the object in use. Pay attention to naming conventions>";
$content = "Hello, OSS!"; // Content of the uploaded file
try {
$ossClient->putObject($bucket, $object, $content);
} catch (OssException $e) {
print $e->getMessage();
}
```
### Operations on buckets
Buckets are the space that you use to manage the stored objects. It is an object management unit for users. Each object must belong to a bucket. You can create a bucket with the following code:
```php
<?php
$bucket= "<Name of the bucket in use. Pay attention to naming conventions>";
try {
$ossClient->createBucket($bucket);
} catch (OssException $e) {
print $e->getMessage();
}
```
### Handle returned results
The OSSClient provides the following two types of returned data from interfaces:
- Put and Delete interfaces: The *PUT* and *DELETE* operations are deemed successful if *null* is returned by the interfaces without *OSSException*.
- Get and List interfaces: The *GET* and *LIST* operations are deemed successful if the desired data is returned by the interfaces without *OSSException*. For example,
```php
<?php
$bucketListInfo = $ossClient->listBuckets();
$bucketList = $bucketListInfo->getBucketList();
foreach($bucketList as $bucket) {
print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreatedate() . "\n");
}
```
In the above code, $bucketListInfo falls into the 'OSS\Model\BucketListInfo' data type.
### Run a sample project
- Modify `samples/Config.php` to complete the configuration information.
- Run `cd samples/ && php RunAll.php`.
### Run a unit test
- Run `composer install` to download the dependent libraries.
- Set the environment variable.
export OSS_ACCESS_KEY_ID=access-key-id
export OSS_ACCESS_KEY_SECRET=access-key-secret
export OSS_ENDPOINT=endpoint
export OSS_BUCKET=bucket-name
- Run `php vendor/bin/phpunit`
## License
- MIT
## Contact us
- [Alibaba Cloud OSS official website](http://oss.aliyun.com).
- [Alibaba Cloud OSS official forum](http://bbs.aliyun.com).
- [Alibaba Cloud OSS official documentation center](http://www.aliyun.com/product/oss#Docs).
- Alibaba Cloud official technical support: [Submit a ticket](https://workorder.console.aliyun.com/#/ticket/createIndex).
[releases-page]: https://github.com/aliyun/aliyun-oss-php-sdk/releases
[phar-composer]: https://github.com/clue/phar-composer
<?php
function classLoader($class)
{
$path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
$file = __DIR__ . DIRECTORY_SEPARATOR .'src'. DIRECTORY_SEPARATOR . $path . '.php';
if (file_exists($file)) {
require_once $file;
}
}
spl_autoload_register('classLoader');
\ No newline at end of file
#! /usr/bin/env bash
# Remove dev deps to reduce phar size
rm -rf composer.lock vendor/
# Generate composer.lock
composer install --no-dev
# Find SDK version
version=$(grep 'const OSS_VERSION' src/OSS/OssClient.php | grep -oE '[0-9.]+')
# Build phar
phar-composer build . aliyun-oss-php-sdk-$version.phar
{
"name": "aliyuncs/oss-sdk-php",
"description": "Aliyun OSS SDK for PHP",
"homepage": "http://www.aliyun.com/product/oss/",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Aliyuncs",
"homepage": "http://www.aliyun.com"
}
],
"require": {
"php":">=5.3"
},
"require-dev" : {
"phpunit/phpunit": "~4.0",
"satooshi/php-coveralls": "~1.0"
},
"minimum-stability": "stable",
"autoload": {
"psr-4": {"OSS\\": "src/OSS"}
}
}
<?php
require_once __DIR__ . '/vendor/autoload.php';
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<phpunit>
<filter>
<whitelist>
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
<logging>
<log type="coverage-clover" target="coverage.xml" />
</logging>
<testsuites>
<testsuite name="FunctionTest">
<directory>./tests</directory>
<exclude>./tests/OSS/Tests/BucketCnameTest.php</exclude>
</testsuite>
</testsuites>
</phpunit>
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* 简单使用 ****************************************************************
//创建bucket
$ossClient->createBucket($bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE);
Common::println("bucket $bucket created");
// 判断Bucket是否存在
$doesExist = $ossClient->doesBucketExist($bucket);
Common::println("bucket $bucket exist? " . ($doesExist ? "yes" : "no"));
// 获取Bucket列表
$bucketListInfo = $ossClient->listBuckets();
// 设置bucket的ACL
$ossClient->putBucketAcl($bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE);
Common::println("bucket $bucket acl put");
// 获取bucket的ACL
$acl = $ossClient->getBucketAcl($bucket);
Common::println("bucket $bucket acl get: " . $acl);
//******************************* 完整用法参考下面函数 ****************************************************
createBucket($ossClient, $bucket);
doesBucketExist($ossClient, $bucket);
deleteBucket($ossClient, $bucket);
putBucketAcl($ossClient, $bucket);
getBucketAcl($ossClient, $bucket);
listBuckets($ossClient);
/**
* 创建一个存储空间
* acl 指的是bucket的访问控制权限,有三种,私有读写,公共读私有写,公共读写。
* 私有读写就是只有bucket的拥有者或授权用户才有权限操作
* 三种权限分别对应 (OssClient::OSS_ACL_TYPE_PRIVATE,OssClient::OSS_ACL_TYPE_PUBLIC_READ, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE)
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 要创建的存储空间名称
* @return null
*/
function createBucket($ossClient, $bucket)
{
try {
$ossClient->createBucket($bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* 判断Bucket是否存在
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
*/
function doesBucketExist($ossClient, $bucket)
{
try {
$res = $ossClient->doesBucketExist($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
if ($res === true) {
print(__FUNCTION__ . ": OK" . "\n");
} else {
print(__FUNCTION__ . ": FAILED" . "\n");
}
}
/**
* 删除bucket,如果bucket不为空则bucket无法删除成功, 不为空表示bucket既没有object,也没有未完成的multipart上传时的parts
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 待删除的存储空间名称
* @return null
*/
function deleteBucket($ossClient, $bucket)
{
try {
$ossClient->deleteBucket($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* 设置bucket的acl配置
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function putBucketAcl($ossClient, $bucket)
{
$acl = OssClient::OSS_ACL_TYPE_PRIVATE;
try {
$ossClient->putBucketAcl($bucket, $acl);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* 获取bucket的acl配置
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function getBucketAcl($ossClient, $bucket)
{
try {
$res = $ossClient->getBucketAcl($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print('acl: ' . $res);
}
/**
* 列出用户所有的Bucket
*
* @param OssClient $ossClient OssClient实例
* @return null
*/
function listBuckets($ossClient)
{
$bucketList = null;
try {
$bucketListInfo = $ossClient->listBuckets();
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
$bucketList = $bucketListInfo->getBucketList();
foreach ($bucketList as $bucket) {
print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreatedate() . "\n");
}
}
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\CorsConfig;
use OSS\Model\CorsRule;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* 简单使用 ****************************************************************
// 设置cors配置
$corsConfig = new CorsConfig();
$rule = new CorsRule();
$rule->addAllowedHeader("x-oss-header");
$rule->addAllowedOrigin("http://www.b.com");
$rule->addAllowedMethod("POST");
$rule->setMaxAgeSeconds(10);
$corsConfig->addRule($rule);
$ossClient->putBucketCors($bucket, $corsConfig);
Common::println("bucket $bucket corsConfig created:" . $corsConfig->serializeToXml());
// 获取cors配置
$corsConfig = $ossClient->getBucketCors($bucket);
Common::println("bucket $bucket corsConfig fetched:" . $corsConfig->serializeToXml());
// 删除cors配置
$ossClient->deleteBucketCors($bucket);
Common::println("bucket $bucket corsConfig deleted");
//******************************* 完整用法参考下面函数 *****************************************************
putBucketCors($ossClient, $bucket);
getBucketCors($ossClient, $bucket);
deleteBucketCors($ossClient, $bucket);
getBucketCors($ossClient, $bucket);
/**
* 设置bucket的cors配置
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function putBucketCors($ossClient, $bucket)
{
$corsConfig = new CorsConfig();
$rule = new CorsRule();
$rule->addAllowedHeader("x-oss-header");
$rule->addAllowedOrigin("http://www.b.com");
$rule->addAllowedMethod("POST");
$rule->setMaxAgeSeconds(10);
$corsConfig->addRule($rule);
try {
$ossClient->putBucketCors($bucket, $corsConfig);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* 获取并打印bucket的cors配置
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function getBucketCors($ossClient, $bucket)
{
$corsConfig = null;
try {
$corsConfig = $ossClient->getBucketCors($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print($corsConfig->serializeToXml() . "\n");
}
/**
* 删除bucket的所有的cors配置
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function deleteBucketCors($ossClient, $bucket)
{
try {
$ossClient->deleteBucketCors($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\LifecycleAction;
use OSS\Model\LifecycleConfig;
use OSS\Model\LifecycleRule;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//******************************* 简单使用 *******************************************************
//设置lifecycle规则
$lifecycleConfig = new LifecycleConfig();
$actions = array();
$actions[] = new LifecycleAction("Expiration", "Days", 3);
$lifecycleRule = new LifecycleRule("delete obsoleted files", "obsoleted/", "Enabled", $actions);
$lifecycleConfig->addRule($lifecycleRule);
$ossClient->putBucketLifecycle($bucket, $lifecycleConfig);
Common::println("bucket $bucket lifecycleConfig created:" . $lifecycleConfig->serializeToXml());
//获取lifecycle规则
$lifecycleConfig = $ossClient->getBucketLifecycle($bucket);
Common::println("bucket $bucket lifecycleConfig fetched:" . $lifecycleConfig->serializeToXml());
//删除bucket的lifecycle配置
$ossClient->deleteBucketLifecycle($bucket);
Common::println("bucket $bucket lifecycleConfig deleted");
//***************************** 完整用法参考下面函数 ***********************************************
putBucketLifecycle($ossClient, $bucket);
getBucketLifecycle($ossClient, $bucket);
deleteBucketLifecycle($ossClient, $bucket);
getBucketLifecycle($ossClient, $bucket);
/**
* 设置bucket的生命周期配置
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function putBucketLifecycle($ossClient, $bucket)
{
$lifecycleConfig = new LifecycleConfig();
$actions = array();
$actions[] = new LifecycleAction(OssClient::OSS_LIFECYCLE_EXPIRATION, OssClient::OSS_LIFECYCLE_TIMING_DAYS, 3);
$lifecycleRule = new LifecycleRule("delete obsoleted files", "obsoleted/", "Enabled", $actions);
$lifecycleConfig->addRule($lifecycleRule);
$actions = array();
$actions[] = new LifecycleAction(OssClient::OSS_LIFECYCLE_EXPIRATION, OssClient::OSS_LIFECYCLE_TIMING_DATE, '2022-10-12T00:00:00.000Z');
$lifecycleRule = new LifecycleRule("delete temporary files", "temporary/", "Enabled", $actions);
$lifecycleConfig->addRule($lifecycleRule);
try {
$ossClient->putBucketLifecycle($bucket, $lifecycleConfig);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* 获取bucket的生命周期配置
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function getBucketLifecycle($ossClient, $bucket)
{
$lifecycleConfig = null;
try {
$lifecycleConfig = $ossClient->getBucketLifecycle($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print($lifecycleConfig->serializeToXml() . "\n");
}
/**
* 删除bucket的生命周期配置
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function deleteBucketLifecycle($ossClient, $bucket)
{
try {
$ossClient->deleteBucketLifecycle($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//*******************************简单使用***************************************************************
// 设置Bucket访问日志记录规则, 访问日志文件的存放位置是同bucket下的access.log前缀的文件
$ossClient->putBucketLogging($bucket, $bucket, "access.log", array());
Common::println("bucket $bucket lifecycleConfig created");
// 获取Bucket访问日志记录规则
$loggingConfig = $ossClient->getBucketLogging($bucket, array());
Common::println("bucket $bucket lifecycleConfig fetched:" . $loggingConfig->serializeToXml());
// 删除Bucket访问日志记录规则
$loggingConfig = $ossClient->getBucketLogging($bucket, array());
Common::println("bucket $bucket lifecycleConfig deleted");
//******************************* 完整用法参考下面函数 ****************************************************
putBucketLogging($ossClient, $bucket);
getBucketLogging($ossClient, $bucket);
deleteBucketLogging($ossClient, $bucket);
getBucketLogging($ossClient, $bucket);
/**
* 设置bucket的Logging配置
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function putBucketLogging($ossClient, $bucket)
{
$option = array();
//访问日志存放在本bucket下
$targetBucket = $bucket;
$targetPrefix = "access.log";
try {
$ossClient->putBucketLogging($bucket, $targetBucket, $targetPrefix, $option);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* 获取bucket的Logging配置
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function getBucketLogging($ossClient, $bucket)
{
$loggingConfig = null;
$options = array();
try {
$loggingConfig = $ossClient->getBucketLogging($bucket, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print($loggingConfig->serializeToXml() . "\n");
}
/**
* 删除bucket的Logging配置
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function deleteBucketLogging($ossClient, $bucket)
{
try {
$ossClient->deleteBucketLogging($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use \OSS\Model\RefererConfig;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//******************************* 简单使用 ****************************************************************
//设置referer白名单
$refererConfig = new RefererConfig();
$refererConfig->setAllowEmptyReferer(true);
$refererConfig->addReferer("www.aliiyun.com");
$refererConfig->addReferer("www.aliiyuncs.com");
$ossClient->putBucketReferer($bucket, $refererConfig);
Common::println("bucket $bucket refererConfig created:" . $refererConfig->serializeToXml());
//获取Referer白名单
$refererConfig = $ossClient->getBucketReferer($bucket);
Common::println("bucket $bucket refererConfig fetched:" . $refererConfig->serializeToXml());
//删除referer白名单
$refererConfig = new RefererConfig();
$ossClient->putBucketReferer($bucket, $refererConfig);
Common::println("bucket $bucket refererConfig deleted");
//******************************* 完整用法参考下面函数 ****************************************************
putBucketReferer($ossClient, $bucket);
getBucketReferer($ossClient, $bucket);
deleteBucketReferer($ossClient, $bucket);
getBucketReferer($ossClient, $bucket);
/**
* 设置bucket的防盗链配置
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function putBucketReferer($ossClient, $bucket)
{
$refererConfig = new RefererConfig();
$refererConfig->setAllowEmptyReferer(true);
$refererConfig->addReferer("www.aliiyun.com");
$refererConfig->addReferer("www.aliiyuncs.com");
try {
$ossClient->putBucketReferer($bucket, $refererConfig);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* 获取bucket的防盗链配置
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function getBucketReferer($ossClient, $bucket)
{
$refererConfig = null;
try {
$refererConfig = $ossClient->getBucketReferer($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print($refererConfig->serializeToXml() . "\n");
}
/**
* 删除bucket的防盗链配置
* Referer白名单不能直接清空,只能通过重新设置来覆盖之前的规则。
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function deleteBucketReferer($ossClient, $bucket)
{
$refererConfig = new RefererConfig();
try {
$ossClient->putBucketReferer($bucket, $refererConfig);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\WebsiteConfig;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//*******************************简单使用***************************************************************
// 设置Bucket的静态网站托管模式
$websiteConfig = new WebsiteConfig("index.html", "error.html");
$ossClient->putBucketWebsite($bucket, $websiteConfig);
Common::println("bucket $bucket websiteConfig created:" . $websiteConfig->serializeToXml());
// 查看Bucket的静态网站托管状态
$websiteConfig = $ossClient->getBucketWebsite($bucket);
Common::println("bucket $bucket websiteConfig fetched:" . $websiteConfig->serializeToXml());
// 删除Bucket的静态网站托管模式
$ossClient->deleteBucketWebsite($bucket);
Common::println("bucket $bucket websiteConfig deleted");
//******************************* 完整用法参考下面函数 ****************************************************
putBucketWebsite($ossClient, $bucket);
getBucketWebsite($ossClient, $bucket);
deleteBucketWebsite($ossClient, $bucket);
getBucketWebsite($ossClient, $bucket);
/**
* 设置bucket的静态网站托管模式配置
*
* @param $ossClient OssClient
* @param $bucket string 存储空间名称
* @return null
*/
function putBucketWebsite($ossClient, $bucket)
{
$websiteConfig = new WebsiteConfig("index.html", "error.html");
try {
$ossClient->putBucketWebsite($bucket, $websiteConfig);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* 获取bucket的静态网站托管状态
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function getBucketWebsite($ossClient, $bucket)
{
$websiteConfig = null;
try {
$websiteConfig = $ossClient->getBucketWebsite($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print($websiteConfig->serializeToXml() . "\n");
}
/**
* 删除bucket的静态网站托管模式配置
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function deleteBucketWebsite($ossClient, $bucket)
{
try {
$ossClient->deleteBucketWebsite($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//*******************************简单使用***************************************************************
/** putObject 使用callback上传内容到oss文件
* callbackurl参数指定请求回调的服务器url
* callbackbodytype参数可为application/json或application/x-www-form-urlencoded, 可选参数,默认为application/x-www-form-urlencoded
* OSS_CALLBACK_VAR参数可以不设置
*/
$url =
'{
"callbackUrl":"callback.oss-demo.com:23450",
"callbackHost":"oss-cn-hangzhou.aliyuncs.com",
"callbackBody":"bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}&my_var1=${x:var1}&my_var2=${x:var2}",
"callbackBodyType":"application/x-www-form-urlencoded"
}';
$var =
'{
"x:var1":"value1",
"x:var2":"值2"
}';
$options = array(OssClient::OSS_CALLBACK => $url,
OssClient::OSS_CALLBACK_VAR => $var
);
$result = $ossClient->putObject($bucket, "b.file", "random content", $options);
Common::println($result['body']);
Common::println($result['info']['http_code']);
/**
* completeMultipartUpload 使用callback上传内容到oss文件
* callbackurl参数指定请求回调的服务器url
* callbackbodytype参数可为application/json或application/x-www-form-urlencoded, 可选参数,默认为application/x-www-form-urlencoded
* OSS_CALLBACK_VAR参数可以不设置
*/
$object = "multipart-callback-test.txt";
$copiedObject = "multipart-callback-test.txt.copied";
$ossClient->putObject($bucket, $copiedObject, file_get_contents(__FILE__));
/**
* step 1. 初始化一个分块上传事件, 也就是初始化上传Multipart, 获取upload id
*/
$upload_id = $ossClient->initiateMultipartUpload($bucket, $object);
/**
* step 2. uploadPartCopy
*/
$copyId = 1;
$eTag = $ossClient->uploadPartCopy($bucket, $copiedObject, $bucket, $object, $copyId, $upload_id);
$upload_parts[] = array(
'PartNumber' => $copyId,
'ETag' => $eTag,
);
$listPartsInfo = $ossClient->listParts($bucket, $object, $upload_id);
/**
* step 3.
*/
$json =
'{
"callbackUrl":"callback.oss-demo.com:23450",
"callbackHost":"oss-cn-hangzhou.aliyuncs.com",
"callbackBody":"{\"mimeType\":${mimeType},\"size\":${size},\"x:var1\":${x:var1},\"x:var2\":${x:var2}}",
"callbackBodyType":"application/json"
}';
$var =
'{
"x:var1":"value1",
"x:var2":"值2"
}';
$options = array(OssClient::OSS_CALLBACK => $json,
OssClient::OSS_CALLBACK_VAR => $var);
$result = $ossClient->completeMultipartUpload($bucket, $object, $upload_id, $upload_parts, $options);
Common::println($result['body']);
Common::println($result['info']['http_code']);
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
require_once __DIR__ . '/Config.php';
use OSS\OssClient;
use OSS\Core\OssException;
/**
* Class Common
*
* 示例程序【Samples/*.php】 的Common类,用于获取OssClient实例和其他公用方法
*/
class Common
{
const endpoint = Config::OSS_ENDPOINT;
const accessKeyId = Config::OSS_ACCESS_ID;
const accessKeySecret = Config::OSS_ACCESS_KEY;
const bucket = Config::OSS_TEST_BUCKET;
/**
* 根据Config配置,得到一个OssClient实例
*
* @return OssClient 一个OssClient实例
*/
public static function getOssClient()
{
try {
$ossClient = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint, false);
} catch (OssException $e) {
printf(__FUNCTION__ . "creating OssClient instance: FAILED\n");
printf($e->getMessage() . "\n");
return null;
}
return $ossClient;
}
public static function getBucketName()
{
return self::bucket;
}
/**
* 工具方法,创建一个存储空间,如果发生异常直接exit
*/
public static function createBucket()
{
$ossClient = self::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = self::getBucketName();
$acl = OssClient::OSS_ACL_TYPE_PUBLIC_READ;
try {
$ossClient->createBucket($bucket, $acl);
} catch (OssException $e) {
$message = $e->getMessage();
if (\OSS\Core\OssUtil::startsWith($message, 'http status: 403')) {
echo "Please Check your AccessKeyId and AccessKeySecret" . "\n";
exit(0);
} elseif (strpos($message, "BucketAlreadyExists") !== false) {
echo "Bucket already exists. Please check whether the bucket belongs to you, or it was visited with correct endpoint. " . "\n";
exit(0);
}
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
public static function println($message)
{
if (!empty($message)) {
echo strval($message) . "\n";
}
}
}
Common::createBucket();
<?php
/**
* Class Config
*
* 执行Sample示例所需要的配置,用户在这里配置好Endpoint,AccessId, AccessKey和Sample示例操作的
* bucket后,便可以直接运行RunAll.php, 运行所有的samples
*/
final class Config
{
const OSS_ACCESS_ID = '';
const OSS_ACCESS_KEY = '';
const OSS_ENDPOINT = '';
const OSS_TEST_BUCKET = '';
}
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
$bucketName = Common::getBucketName();
$object = "example.jpg";
$ossClient = Common::getOssClient();
$download_file = "download.jpg";
if (is_null($ossClient)) exit(1);
//*******************************简单使用***************************************************************
// 先把本地的example.jpg上传到指定$bucket, 命名为$object
$ossClient->uploadFile($bucketName, $object, "example.jpg");
// 图片缩放
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => "image/resize,m_fixed,h_100,w_100", );
$ossClient->getObject($bucketName, $object, $options);
printImage("imageResize",$download_file);
// 图片裁剪
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => "image/crop,w_100,h_100,x_100,y_100,r_1", );
$ossClient->getObject($bucketName, $object, $options);
printImage("iamgeCrop", $download_file);
// 图片旋转
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => "image/rotate,90", );
$ossClient->getObject($bucketName, $object, $options);
printImage("imageRotate", $download_file);
// 图片锐化
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => "image/sharpen,100", );
$ossClient->getObject($bucketName, $object, $options);
printImage("imageSharpen", $download_file);
// 图片水印
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => "image/watermark,text_SGVsbG8g5Zu-54mH5pyN5YqhIQ", );
$ossClient->getObject($bucketName, $object, $options);
printImage("imageWatermark", $download_file);
// 图片格式转换
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => "image/format,png", );
$ossClient->getObject($bucketName, $object, $options);
printImage("imageFormat", $download_file);
// 获取图片信息
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => "image/info", );
$ossClient->getObject($bucketName, $object, $options);
printImage("imageInfo", $download_file);
/**
* 生成一个带签名的可用于浏览器直接打开的url, URL的有效期是3600秒
*/
$timeout = 3600;
$options = array(
OssClient::OSS_PROCESS => "image/resize,m_lfit,h_100,w_100",
);
$signedUrl = $ossClient->signUrl($bucketName, $object, $timeout, "GET", $options);
Common::println("rtmp url: \n" . $signedUrl);
//最后删除上传的$object
$ossClient->deleteObject($bucketName, $object);
function printImage($func, $imageFile)
{
$array = getimagesize($imageFile);
Common::println("$func, image width: " . $array[0]);
Common::println("$func, image height: " . $array[1]);
Common::println("$func, image type: " . ($array[2] === 2 ? 'jpg' : 'png'));
Common::println("$func, image size: " . ceil(filesize($imageFile)));
}
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Model\LiveChannelConfig;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//******************************* 简单使用 *******************************************************
/**
创建一个直播频道
频道的名称是test_rtmp_live。直播生成的m3u8文件叫做test.m3u8,该索引文件包含3片ts文件,每片ts文件的时长为5秒(这只是一个建议值,具体的时长取决于关键帧)。
*/
$config = new LiveChannelConfig(array(
'description' => 'live channel test',
'type' => 'HLS',
'fragDuration' => 10,
'fragCount' => 5,
'playListName' => 'hello.m3u8'
));
$info = $ossClient->putBucketLiveChannel($bucket, 'test_rtmp_live', $config);
Common::println("bucket $bucket liveChannel created:\n" .
"live channel name: ". $info->getName() . "\n" .
"live channel description: ". $info->getDescription() . "\n" .
"publishurls: ". $info->getPublishUrls()[0] . "\n" .
"playurls: ". $info->getPlayUrls()[0] . "\n");
/**
对创建好的频道,可以使用listBucketLiveChannels来进行列举已达到管理的目的。
prefix可以按照前缀过滤list出来的频道。
max_keys表示迭代器内部一次list出来的频道的最大数量,这个值最大不能超过1000,不填写的话默认为100。
*/
$list = $ossClient->listBucketLiveChannels($bucket);
Common::println("bucket $bucket listLiveChannel:\n" .
"list live channel prefix: ". $list->getPrefix() . "\n" .
"list live channel marker: ". $list->getMarker() . "\n" .
"list live channel maxkey: ". $list->getMaxKeys() . "\n" .
"list live channel IsTruncated: ". $list->getIsTruncated() . "\n" .
"list live channel getNextMarker: ". $list->getNextMarker() . "\n");
foreach($list->getChannelList() as $list)
{
Common::println("bucket $bucket listLiveChannel:\n" .
"list live channel IsTruncated: ". $list->getName() . "\n" .
"list live channel Description: ". $list->getDescription() . "\n" .
"list live channel Status: ". $list->getStatus() . "\n" .
"list live channel getNextMarker: ". $list->getLastModified() . "\n");
}
/**
创建直播频道之后拿到推流用的play_url(rtmp推流的url,如果Bucket不是公共读写权限那么还需要带上签名,见下文示例)和推流用的publish_url(推流产生的m3u8文件的url)
*/
$play_url = $ossClient->signRtmpUrl($bucket, "test_rtmp_live", 3600, array('params' => array('playlistName' => 'playlist.m3u8')));
Common::println("bucket $bucket rtmp url: \n" . $play_url);
$play_url = $ossClient->signRtmpUrl($bucket, "test_rtmp_live", 3600);
Common::println("bucket $bucket rtmp url: \n" . $play_url);
/**
创建好直播频道,如果想把这个频道禁用掉(断掉正在推的流或者不再允许向一个地址推流),应该使用putLiveChannelStatus接口,将频道的status改成“Disabled”,如果要将一个禁用状态的频道启用,那么也是调用这个接口,将status改成“Enabled”
*/
$resp = $ossClient->putLiveChannelStatus($bucket, "test_rtmp_live", "enabled");
/**
创建好直播频道之后调用getLiveChannelInfo可以得到频道相关的信息
*/
$info = $ossClient->getLiveChannelInfo($bucket, 'test_rtmp_live');
Common::println("bucket $bucket LiveChannelInfo:\n" .
"live channel info description: ". $info->getDescription() . "\n" .
"live channel info status: ". $info->getStatus() . "\n" .
"live channel info type: ". $info->getType() . "\n" .
"live channel info fragDuration: ". $info->getFragDuration() . "\n" .
"live channel info fragCount: ". $info->getFragCount() . "\n" .
"live channel info playListName: ". $info->getPlayListName() . "\n");
/**
如果想查看一个频道历史推流记录,可以调用getLiveChannelHistory。目前最多可以看到10次推流的记录
*/
$history = $ossClient->getLiveChannelHistory($bucket, "test_rtmp_live");
if (count($history->getLiveRecordList()) != 0)
{
foreach($history->getLiveRecordList() as $recordList)
{
Common::println("bucket $bucket liveChannelHistory:\n" .
"live channel history startTime: ". $recordList->getStartTime() . "\n" .
"live channel history endTime: ". $recordList->getEndTime() . "\n" .
"live channel history remoteAddr: ". $recordList->getRemoteAddr() . "\n");
}
}
/**
对于正在推流的频道调用get_live_channel_stat可以获得流的状态信息。
如果频道正在推流,那么stat_result中的所有字段都有意义。
如果频道闲置或者处于“Disabled”状态,那么status为“Idle”或“Disabled”,其他字段无意义。
*/
$status = $ossClient->getLiveChannelStatus($bucket, "test_rtmp_live");
Common::println("bucket $bucket listLiveChannel:\n" .
"live channel status status: ". $status->getStatus() . "\n" .
"live channel status ConnectedTime: ". $status->getConnectedTime() . "\n" .
"live channel status VideoWidth: ". $status->getVideoWidth() . "\n" .
"live channel status VideoHeight: ". $status->getVideoHeight() . "\n" .
"live channel status VideoFrameRate: ". $status->getVideoFrameRate() . "\n" .
"live channel status VideoBandwidth: ". $status->getVideoBandwidth() . "\n" .
"live channel status VideoCodec: ". $status->getVideoCodec() . "\n" .
"live channel status AudioBandwidth: ". $status->getAudioBandwidth() . "\n" .
"live channel status AudioSampleRate: ". $status->getAudioSampleRate() . "\n" .
"live channel status AdioCodec: ". $status->getAudioCodec() . "\n");
/**
* 如果希望利用直播推流产生的ts文件生成一个点播列表,可以使用postVodPlaylist方法。
* 指定起始时间为当前时间减去60秒,结束时间为当前时间,这意味着将生成一个长度为60秒的点播视频。
* 播放列表指定为“vod_playlist.m3u8”,也就是说这个接口调用成功之后会在OSS上生成一个名叫“vod_playlist.m3u8”的播放列表文件。
*/
$current_time = time();
$ossClient->postVodPlaylist($bucket,
"test_rtmp_live", "vod_playlist.m3u8",
array('StartTime' => $current_time - 60,
'EndTime' => $current_time)
);
/**
* 如果一个直播频道已经不打算再使用了,那么可以调用delete_live_channel来删除频道。
*/
$ossClient->deleteBucketLiveChannel($bucket, "test_rtmp_live");
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssUtil;
use OSS\Core\OssException;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//*******************************简单使用***************************************************************
/**
* 查看完整用法中的 "putObjectByRawApis"函数,查看使用基础的分片上传api进行文件上传,用户可以基于这个自行实现断点续传等功能
*/
// 使用分片上传接口上传文件, 接口会根据文件大小决定是使用普通上传还是分片上传
$ossClient->multiuploadFile($bucket, "file.php", __FILE__, array());
Common::println("local file " . __FILE__ . " is uploaded to the bucket $bucket, file.php");
// 上传本地目录到bucket内的targetdir子目录中
$ossClient->uploadDir($bucket, "targetdir", __DIR__);
Common::println("local dir " . __DIR__ . " is uploaded to the bucket $bucket, targetdir/");
// 列出当前未完成的分片上传
$listMultipartUploadInfo = $ossClient->listMultipartUploads($bucket, array());
//******************************* 完整用法参考下面函数 ****************************************************
multiuploadFile($ossClient, $bucket);
putObjectByRawApis($ossClient, $bucket);
uploadDir($ossClient, $bucket);
listMultipartUploads($ossClient, $bucket);
/**
* 通过multipart上传文件
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
*/
function multiuploadFile($ossClient, $bucket)
{
$object = "test/multipart-test.txt";
$file = __FILE__;
$options = array();
try {
$ossClient->multiuploadFile($bucket, $object, $file, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* 使用基本的api分阶段进行分片上传
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @throws OssException
*/
function putObjectByRawApis($ossClient, $bucket)
{
$object = "test/multipart-test.txt";
/**
* step 1. 初始化一个分块上传事件, 也就是初始化上传Multipart, 获取upload id
*/
try {
$uploadId = $ossClient->initiateMultipartUpload($bucket, $object);
} catch (OssException $e) {
printf(__FUNCTION__ . ": initiateMultipartUpload FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": initiateMultipartUpload OK" . "\n");
/*
* step 2. 上传分片
*/
$partSize = 10 * 1024 * 1024;
$uploadFile = __FILE__;
$uploadFileSize = filesize($uploadFile);
$pieces = $ossClient->generateMultiuploadParts($uploadFileSize, $partSize);
$responseUploadPart = array();
$uploadPosition = 0;
$isCheckMd5 = true;
foreach ($pieces as $i => $piece) {
$fromPos = $uploadPosition + (integer)$piece[$ossClient::OSS_SEEK_TO];
$toPos = (integer)$piece[$ossClient::OSS_LENGTH] + $fromPos - 1;
$upOptions = array(
$ossClient::OSS_FILE_UPLOAD => $uploadFile,
$ossClient::OSS_PART_NUM => ($i + 1),
$ossClient::OSS_SEEK_TO => $fromPos,
$ossClient::OSS_LENGTH => $toPos - $fromPos + 1,
$ossClient::OSS_CHECK_MD5 => $isCheckMd5,
);
if ($isCheckMd5) {
$contentMd5 = OssUtil::getMd5SumForFile($uploadFile, $fromPos, $toPos);
$upOptions[$ossClient::OSS_CONTENT_MD5] = $contentMd5;
}
//2. 将每一分片上传到OSS
try {
$responseUploadPart[] = $ossClient->uploadPart($bucket, $object, $uploadId, $upOptions);
} catch (OssException $e) {
printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} FAILED\n");
printf($e->getMessage() . "\n");
return;
}
printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} OK\n");
}
$uploadParts = array();
foreach ($responseUploadPart as $i => $eTag) {
$uploadParts[] = array(
'PartNumber' => ($i + 1),
'ETag' => $eTag,
);
}
/**
* step 3. 完成上传
*/
try {
$ossClient->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts);
} catch (OssException $e) {
printf(__FUNCTION__ . ": completeMultipartUpload FAILED\n");
printf($e->getMessage() . "\n");
return;
}
printf(__FUNCTION__ . ": completeMultipartUpload OK\n");
}
/**
* 按照目录上传文件
*
* @param OssClient $ossClient OssClient
* @param string $bucket 存储空间名称
*
*/
function uploadDir($ossClient, $bucket)
{
$localDirectory = ".";
$prefix = "samples/codes";
try {
$ossClient->uploadDir($bucket, $prefix, $localDirectory);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
printf(__FUNCTION__ . ": completeMultipartUpload OK\n");
}
/**
* 获取当前未完成的分片上传列表
*
* @param $ossClient OssClient
* @param $bucket string
*/
function listMultipartUploads($ossClient, $bucket)
{
$options = array(
'max-uploads' => 100,
'key-marker' => '',
'prefix' => '',
'upload-id-marker' => ''
);
try {
$listMultipartUploadInfo = $ossClient->listMultipartUploads($bucket, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": listMultipartUploads FAILED\n");
printf($e->getMessage() . "\n");
return;
}
printf(__FUNCTION__ . ": listMultipartUploads OK\n");
$listUploadInfo = $listMultipartUploadInfo->getUploads();
var_dump($listUploadInfo);
}
<?php
error_reporting(E_ALL | E_NOTICE);
require_once __DIR__ . '/Bucket.php';
require_once __DIR__ . '/BucketCors.php';
require_once __DIR__ . '/BucketLifecycle.php';
require_once __DIR__ . '/BucketReferer.php';
require_once __DIR__ . '/BucketLogging.php';
require_once __DIR__ . '/BucketWebsite.php';
require_once __DIR__ . '/Signature.php';
require_once __DIR__ . '/Object.php';
require_once __DIR__ . '/MultipartUpload.php';
\ No newline at end of file
<?php
require_once __DIR__ . '/Common.php';
use OSS\Http\RequestCore;
use OSS\Http\ResponseCore;
use OSS\OssClient;
use OSS\Core\OssException;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//******************************* 简单使用 ***************************************************************
$ossClient->uploadFile($bucket, "a.file", __FILE__);
// 生成GetObject的签名url,用户可以使用这个url直接在浏览器下载
$signedUrl = $ossClient->signUrl($bucket, "a.file", 3600);
Common::println($signedUrl);
// 生成用于putObject的签名URL,用户可以直接用put方法使用这个url上传文件到 "a.file"
$signedUrl = $ossClient->signUrl($bucket, "a.file", "3600", "PUT");
Common::println($signedUrl);
// 生成从本地文件上传PutObject的签名url, 用户可以直接使用这个url把本地文件上传到 "a.file"
$signedUrl = $ossClient->signUrl($bucket, "a.file", 3600, "PUT", array('Content-Type' => 'txt'));
Common::println($signedUrl);
//******************************* 完整用法参考下面函数 ****************************************************
getSignedUrlForPuttingObject($ossClient, $bucket);
getSignedUrlForPuttingObjectFromFile($ossClient, $bucket);
getSignedUrlForGettingObject($ossClient, $bucket);
/**
* 生成GetObject的签名url,主要用于私有权限下的读访问控制
*
* @param $ossClient OssClient OssClient实例
* @param $bucket string 存储空间名称
* @return null
*/
function getSignedUrlForGettingObject($ossClient, $bucket)
{
$object = "test/test-signature-test-upload-and-download.txt";
$timeout = 3600;
try {
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n");
/**
* 可以类似的代码来访问签名的URL,也可以输入到浏览器中去访问
*/
$request = new RequestCore($signedUrl);
$request->set_method('GET');
$request->add_header('Content-Type', '');
$request->send_request();
$res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code());
if ($res->isOK()) {
print(__FUNCTION__ . ": OK" . "\n");
} else {
print(__FUNCTION__ . ": FAILED" . "\n");
};
}
/**
* 生成PutObject的签名url,主要用于私有权限下的写访问控制
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @return null
* @throws OssException
*/
function getSignedUrlForPuttingObject($ossClient, $bucket)
{
$object = "test/test-signature-test-upload-and-download.txt";
$timeout = 3600;
$options = NULL;
try {
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT");
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n");
$content = file_get_contents(__FILE__);
$request = new RequestCore($signedUrl);
$request->set_method('PUT');
$request->add_header('Content-Type', '');
$request->add_header('Content-Length', strlen($content));
$request->set_body($content);
$request->send_request();
$res = new ResponseCore($request->get_response_header(),
$request->get_response_body(), $request->get_response_code());
if ($res->isOK()) {
print(__FUNCTION__ . ": OK" . "\n");
} else {
print(__FUNCTION__ . ": FAILED" . "\n");
};
}
/**
* 生成PutObject的签名url,主要用于私有权限下的写访问控制, 用户可以利用生成的signedUrl
* 从文件上传文件
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @throws OssException
*/
function getSignedUrlForPuttingObjectFromFile($ossClient, $bucket)
{
$file = __FILE__;
$object = "test/test-signature-test-upload-and-download.txt";
$timeout = 3600;
$options = array('Content-Type' => 'txt');
try {
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT", $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n");
$request = new RequestCore($signedUrl);
$request->set_method('PUT');
$request->add_header('Content-Type', 'txt');
$request->set_read_file($file);
$request->set_read_stream_size(filesize($file));
$request->send_request();
$res = new ResponseCore($request->get_response_header(),
$request->get_response_body(), $request->get_response_code());
if ($res->isOK()) {
print(__FUNCTION__ . ": OK" . "\n");
} else {
print(__FUNCTION__ . ": FAILED" . "\n");
};
}
\ No newline at end of file
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment