php之通过file_get_contents模拟post请求并携带cookie
直接看代码吧,比较亲切,有些特殊场景需要使用。
//sevstudio //上传到OSS function toOSS($local_file){ $url = (isHTTPS() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . '/admin/uploadLocalPath2OSS'; $param = [ 'local_path' => $local_file ]; $cookie = getCookie(); $options['http'] = [ 'method' => 'POST', 'timeout' => 60, 'header' => "Content-Type: application/x-www-form-urlencoded;charset=utf-8;\r\n" . implode('',$cookie), // Content-Type: application/x-www-form-urlencoded 'content' => http_build_query($param), ]; $response = file_get_contents( $url, false, stream_context_create($options) ); $obj = json_decode($response,true); if($obj && isset($obj['code']) && $obj['code'] == 0){ return $obj['data']['url']; } return false; } function isHTTPS(){ if(!isset($_SERVER)) return false; if(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 1 || $_SERVER['HTTPS'] === 'on')) { return true; }elseif(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'){ //Nginx return true; }elseif(isset($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] == 'https'){ return true; }else if(isset($_SERVER['HTTP_X_CLIENT_SCHEME']) && $_SERVER['HTTP_X_CLIENT_SCHEME'] == 'https'){ return true; }elseif ($_SERVER['SERVER_PORT'] == 443) { return true; } return false; } function getCookie(){ $result = []; if($_COOKIE){ foreach($_COOKIE as $k=>$v){ $result[] = "Cookie: {$k}={$v}\r\n"; } } return $result; } //sevstudio
包括请求参数、头信息、含cookie携带