以下是一种常见的方法来防止访客刷浏览量的示例代码:session_start();//启动会话//检查是否存在访问计数器if(!isset($_SESSION['page_views'])){$_SESSION['page_views']=1;//初始化计数器}else{$_SESSION['page_views']++;//增加计数器}//检查访问计数器是否超过限制$max_views=10;//设置最大浏览量if($_SESSION['page_views']>$max_views){//如果超过最大浏览量,执行相应的操作,例如跳转到其他页面或显示错误信息header('Location:error.php');exit;}//继续显示文章内容echo"站三界导航https://www.zhansanjie.com";在上面的代码中,我们使用了会话(Session)来记录访问计数器($_SESSION['page_views'])。每次访问文章页时,我们会增加计数器的值。如果计数器超过了设定的最大浏览量,我们可以执行相应的操作,例如跳转到其他页面或显示错误信息。请注意,这只是一种简单的示例代码,并不能完全防止访客刷浏览量。如果需要更严格的防刷措施,可以考虑使用IP地址限制、验证码、防火墙等更高级的技术手段。
在PHP中,可以采取以下方法来防止接口被盗用:使用API密钥:在每个请求中,都要求客户端提供一个API密钥,该密钥用于验证请求的合法性。服务器端对每个请求进行验证,只有在验证通过的情况下才允许访问接口。//生成API密钥$apiKey='your_api_key';//验证API密钥if($_GET['apiKey']!==$apiKey){die('InvalidAPIkey');}使用访问令牌:在用户登录后,为每个用户生成一个访问令牌。客户端在每个请求中都要包含该令牌,服务器端验证令牌的有效性来确定请求是否合法。//生成访问令牌$accessToken=generateAccessToken($userId);//验证访问令牌if($_GET['accessToken']!==$accessToken){die('Invalidaccesstoken');}使用IP限制:根据客户端的IP地址来限制接口访问。只有特定的IP地址才能访问接口,其他IP地址则被拒绝。//允许访问的IP地址列表$allowedIPs=['127.0.0.1','192.168.0.1'];//验证IP地址if(!in_array($_SERVER['REMOTE_ADDR'],$allowedIPs)){die('Accessdenied');}使用HTTPS:使用HTTPS协议来保证通信的安全性,防止接口请求被劫持和篡改。//强制使用HTTPSif(!isset($_SERVER['HTTPS'])||$_SERVER['HTTPS']!=='on'){header('Location:https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);exit;}请注意,以上代码只是示例,具体的实现方式可能会根据具体的业务需求而有所不同。建议在开发过程中,根据实际情况进行综合考虑和测试。
限制连接速率://每分钟最多允许的请求数量$maxRequestsPerMinute=100;//获取客户端的IP地址$clientIp=$_SERVER['REMOTE_ADDR'];//生成存储客户端请求记录的文件路径$recordFile='/path/to/record/'.$clientIp;//如果记录文件不存在,则创建一个新的if(!file_exists($recordFile)){file_put_contents($recordFile,'0');}//读取记录文件中的请求次数$requestCount=(int)file_get_contents($recordFile);//如果请求次数超过限制,则拒绝请求if($requestCount>=$maxRequestsPerMinute){http_response_code429);//返回429TooManyRequests状态码exit;}//增加请求次数并保存到记录文件中file_put_contents($recordFile,++$requestCount);使用验证码验证:session_start();//生成验证码$code=rand(1000,9999);//将验证码保存到会话中$_SESSION['captcha']=$code;//输出验证码图片header('Content-Type:image/png');$image=imagecreatetruecolor(100,30);$bgColor=imagecolorallocate($image,255,255,255);$textColor=imagecolorallocate($image,0,0,0);imagefill($image,0,0,$bgColor);imagestring($image,5,25,5,$code,$textColor);imagepng($image);imagedestroy($image);IP访问频率限制://获取客户端的IP地址$clientIp=$_SERVER['REMOTE_ADDR'];//生成存储客户端请求记录的文件路径$recordFile='/path/to/record/'.$clientIp;//如果记录文件不存在,则创建一个新的if(!file_exists($recordFile)){file_put_contents($recordFile,time());}//读取记录文件中的最后访问时间$lastAccessTime=(int)file_get_contents($recordFile);//如果距离上次访问时间小于指定的时间间隔,则拒绝请求$timeInterval=1;//1秒if(time()-$lastAccessTime<$timeInterval){http_response_code(429);//返回429TooManyRequests状态码exit;}//更新最后访问时间并保存到记录文件中file_put_contents($recordFile,time());请注意,以上代码只是一些基本的示例,可以根据实际情况进行修改和改进。此外,还可以考虑使用反向代、负载均衡器、防火墙等更高级的防护措施来应对DDoS攻击。
限制IP访问频率:functioncheckRateLimit(){$ip=$_SERVER['REMOTE_ADDR'];$limit=10;//每分钟允许的请求次数$interval=60;//时间间隔(秒)$key='rate_limit_'.$ip;$requests=(int)apc_fetch($key);if($requests>=$limit){//超过请求次数限制,进行相应处理die('请求频率过高,请稍后再试!');}else{$requests++;apc_store($key,$requests,$interval);}}checkRateLimit();验证表单提交:functionvalidateForm(){session_start();$token=$_POST['token'];if(!isset($_SESSION['token'])||$token!==$_SESSION['token']){//表单提交的Token验证失败,进行相应处理die('表单提交验证失败!');}//验证通过,继续处理表单数据//...}validateForm();防止URL跳转攻击:functionvalidateURL(){$referer=$_SERVER['HTTP_REFERER'];$allowedDomain='example.com';//允许的域名if(strpos($referer,$allowedDomain)===false){//非法的跳转来源,进行相应处理die('非法的跳转来源!');}//URL验证通过,继续处理页面逻辑//...}validateURL();这些代码示例可以根据实际情况进行修改和扩展,以适应你的应用程序的需求。请注意,这些方法只是一些常用的防止CC攻击的方法,不能保证100%防止所有类型的攻击。最佳的安全实践是使用多层次的安全措施来保护你的应用程序。
聚合热搜热榜PHP接口API源码,本源码接口均抓取采集各大官网数据。PHP环境为5.6或以上,解压压缩包里面的hotlist.php文件到网站目录然后输入参数输入?type参数内容:zhihu(知乎热榜)weibo(微博热搜)baidu(百度热点)history(历史上的今天)bilihot(哔哩哔哩热搜)biliall(哔哩哔哩全站日榜)sspai(少数派头条)douyin(抖音热搜)CSDN(CSDN头条榜)使用方法访问你的域名地址/hotlist.php?type=?type=(输入参数才能显示内容)示例:访问你的域名地址/hotlist.php?type=zhihuAPI源码<?phpheader("Access-Control-Allow-Origin:*");header("Content-type:application/json;charset=utf-8");date_default_timezone_set("Asia/Shanghai");classApi{//少数派热榜publicfunctionsspai(){$jsonRes=json_decode($this->Curl('https://sspai.com/api/v1/article/tag/page/get?limit=100000&tag=%E7%83%AD%E9%97%A8%E6%96%87%E7%AB%A0',null,null,"https://sspai.com"),true);$tempArr=[];foreach($jsonRes['data']as$k=>$v){array_push($tempArr,['index'=>$k+1,'title'=>$v['title'],'createdAt'=>date('Y-m-d',$v['released_time']),'other'=>$v['author']['nickname'],'like_count'=>$v['like_count'],'comment_count'=>$v['comment_count'],'url'=>'https://sspai.com/post/'.$v['id'],'mobilUrl'=>'https://sspai.com/post/'.$v['id']]);}return['success'=>true,'title'=>'少数派','subtitle'=>'热榜','update_time'=>date('Y-m-dh:i:s',time()),'data'=>$tempArr];}//CSDN头条榜publicfunctioncsdn(){$_resHtml=$this->Curl('https://www.csdn.net',null,"User-Agent:Mozilla/5.0(iPhone;CPUiPhoneOS10_3_1likeMacOSX)AppleWebKit/603.1.30(KHTML,likeGecko)Version/10.0Mobile/14E304Safari/602.1","https://www.csdn.net");preg_match('/window.__INITIAL_STATE__=(.*?);<\/script>/',$_resHtml,$_resHtmlArr);$jsonRes=json_decode($_resHtmlArr[1],true);$tempArr=[];//头条foreach($jsonRes['pageData']['data']['Headimg']as$k=>$v){array_push($tempArr,['index'=>$k+1,'title'=>$v['title'],'url'=>$v['url'],'mobilUrl'=>$v['url']]);}//头条1foreach($jsonRes['pageData']['data']['www-Headlines']as$k=>$v){array_push($tempArr,['index'=>$k+17,'title'=>$v['title'],'url'=>$v['url'],'mobilUrl'=>$v['url']]);}//头条2foreach($jsonRes['pageData']['data']['www-headhot']as$k=>$v){array_push($tempArr,['index'=>$k+48,'title'=>$v['title'],'url'=>$v['url'],'mobilUrl'=>$v['url']]);}return['success'=>true,'title'=>'CSDN','subtitle'=>'头条榜','update_time'=>date('Y-m-dh:i:s',time()),'data'=>$tempArr];}//百度百科历史上的今天publicfunctionhistory(){$month=date('m',time());$day=date('d',time());//当前年月日$today=date('Y年m月d日');//获取接口数据$jsonRes=json_decode($this->Curl('https://baike.baidu.com/cms/home/eventsOnHistory/'.$month.'.json',null,null,"https://baike.baidu.com"),true);$tempArr=[];//统计当日总数$countnum=count($jsonRes[$month][$month.$day])-1;foreach($jsonRes[$month][$month.$day]as$k=>$v){array_push($tempArr,['index'=>$k+1,'title'=>$v['year'].'年-'.strip_tags($v['title']),'url'=>'https://www.douyin.com/search/'.urlencode($v['title']),'mobilUrl'=>'https://www.douyin.com/search/'.urlencode($v['title'])]);}return['success'=>true,'title'=>'百度百科','subtitle'=>'历史上的今天','update_time'=>date('Y-m-dh:i:s',time()),'data'=>$tempArr];}//抖音热搜榜publicfunctiondouyin(){$jsonRes=json_decode($this->Curl('https://www.iesdouyin.com/web/api/v2/hotsearch/billboard/word/',null,null,"https://www.douyin.com"),true);$tempArr=[];foreach($jsonRes['word_list']as$k=>$v){array_push($tempArr,['index'=>$k+1,'title'=>$v['word'],'hot'=>round($v['hot_value']/10000,1).'万','url'=>'https://www.douyin.com/search/'.urlencode($v['word']),'mobilUrl'=>'https://www.douyin.com/search/'.urlencode($v['word'])]);}return['success'=>true,'title'=>'抖音','subtitle'=>'热搜榜','update_time'=>date('Y-m-dh:i:s',time()),'data'=>$tempArr];}//哔哩哔哩全站日榜publicfunctionbilibili_rankall(){$jsonRes=json_decode($this->Curl('https://api.bilibili.com/x/web-interface/ranking/v2?rid=0&type=all',null,null,"https://www.bilibili.com"),true);$tempArr=[];foreach($jsonRes['data']['list']as$k=>$v){array_push($tempArr,['index'=>$k+1,'title'=>$v['title'],'pic'=>$v['pic'],'desc'=>$v['desc'],'hot'=>round($v['stat']['view']/10000,1).'万','url'=>$v['short_link'],'mobilUrl'=>$v['short_link']]);}return['success'=>true,'title'=>'哔哩哔哩','subtitle'=>'全站日榜','update_time'=>date('Y-m-dh:i:s',time()),'data'=>$tempArr];}//哔哩哔哩热搜榜publicfunctionbilibili_hot(){$jsonRes=json_decode($this->Curl('https://app.bilibili.com/x/v2/search/trending/ranking',null,null,"https://www.bilibili.com"),true);$tempArr=[];//return$jsonRes;foreach($jsonRes['data']['list']as$k=>$v){array_push($tempArr,['index'=>$v['position'],'title'=>$v['keyword'],'url'=>'https://search.bilibili.com/all?keyword='.$v['keyword'].'&order=click','mobilUrl'=>'https://search.bilibili.com/all?keyword='.$v['keyword'].'&order=click']);}return['success'=>true,'title'=>'哔哩哔哩','subtitle'=>'热搜榜','update_time'=>date('Y-m-dh:i:s',time()),'data'=>$tempArr];}//知乎热榜热度publicfunctionzhihuHot(){$jsonRes=json_decode($this->Curl('https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total?limit=50&desktop=true',null,null,"https://www.zhihu.com"),true);$tempArr=[];foreach($jsonRes['data']as$k=>$v){preg_match('/\d+/',$v['detail_text'],$hot);array_push($tempArr,['index'=>$k+1,'title'=>$v['target']['title'],'hot'=>$hot[0].'万','url'=>'https://www.zhihu.com/question/'.urlencode($v['target']['id']),'mobilUrl'=>'https://www.zhihu.com/question/'.urlencode($v['target']['id'])]);}return['success'=>true,'title'=>'知乎热榜','subtitle'=>'热度','update_time'=>date('Y-m-dh:i:s',time()),'data'=>$tempArr];}//微博热搜榜publicfunctionwbresou(){$_md5=md5(time());$cookie="Cookie:{$_md5}:FG=1";$jsonRes=json_decode($this->Curl('https://weibo.com/ajax/side/hotSearch',null,$cookie,"https://s.weibo.com"),true);$tempArr=[];foreach($jsonRes['data']['realtime']as$k=>$v){array_push($tempArr,['index'=>$k+1,'title'=>$v['note'],'hot'=>round($v['num']/10000,1).'万','url'=>"https://s.weibo.com/weibo?q=".$v['note']."&Refer=index",'mobilUrl'=>"https://s.weibo.com/weibo?q=".$v['note']."&Refer=index"]);}return['success'=>true,'title'=>'微博','subtitle'=>'热搜榜','update_time'=>date('Y-m-dh:i:s',time()),'data'=>$tempArr];}//百度热点指数publicfunctionbaiduredian(){$_resHtml=str_replace(["\n","\r",""],'',$this->Curl('https://top.baidu.com/board?tab=realtime',null));preg_match('/<!--s-data:(.*?)-->/',$_resHtml,$_resHtmlArr);$jsonRes=json_decode($_resHtmlArr[1],true);//return$jsonRes;$tempArr=[];foreach($jsonRes['data']['cards']as$v){foreach($v['content']as$k=>$_v){array_push($tempArr,['index'=>$k+1,'title'=>$_v['word'],'desc'=>$_v['desc'],'pic'=>$_v['img'],'url'=>$_v['url'],'hot'=>round($_v['hotScore']/10000,1).'万','mobilUrl'=>$_v['appUrl']]);}}return['success'=>true,'title'=>'百度热点','subtitle'=>'指数','update_time'=>date('Y-m-dh:i:s',time()),'data'=>$tempArr];}privatefunctionCurl($url,$header=["accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9","Accept-Encoding:gzip,deflate,br","Accept-Language:zh-CN,zh;q=0.9","Connection:keep-alive","User-Agent:Mozilla/5.0(iPhone;CPUiPhoneOS10_3_1likeMacOSX)AppleWebKit/603.1.30(KHTML,likeGecko)Version/10.0Mobile/14E304Safari/602.1"],$cookie=null,$refer='https://www.baidu.com'){$ip=rand(0,255).'.'.rand(0,255).'.'.rand(0,255).'.'.rand(0,255);$header[]="CLIENT-IP:".$ip;$header[]="X-FORWARDED-FOR:".$ip;$ch=curl_init();curl_setopt($ch,CURLOPT_URL,$url);//设置传输的urlcurl_setopt($ch,CURLOPT_HTTPHEADER,$header);//发送http报头curl_setopt($ch,CURLOPT_COOKIE,$cookie);//设置Cookiecurl_setopt($ch,CURLOPT_REFERER,$refer);//设置Referercurl_setopt($ch,CURLOPT_RETURNTRANSFER,1);curl_setopt($ch,CURLOPT_ENCODING,'gzip,deflate');//解码压缩文件curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);//对认证证书来源的检查curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//从证书中检查SSL加密算法是否存在curl_setopt($ch,CURLOPT_TIMEOUT,5);//设置超时限制防止死循环$output=curl_exec($ch);curl_close($ch);return$output;}}$_type=isset($_GET['type'])?$_GET['type']:'';$API=newApi;switch($_type){case'baidu':$_res=$API->baiduredian();break;case'zhihu':$_res=$API->zhihuHot();break;case'weibo':$_res=$API->wbresou();break;case'bilihot':$_res=$API->bilibili_hot();break;case'biliall':$_res=$API->bilibili_rankall();break;case'douyin':$_res=$API->douyin();break;case'history':$_res=$API->history();break;case'csdn':$_res=$API->csdn();break;case'sspai':$_res=$API->sspai();break;default:$_res=['success'=>false,'message'=>'参数不完整'];break;}$_res['copyright']='聚合热搜榜';exit(json_encode($_res,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));?>
//1.构建API请求的URL$site='example.com';//将example.com替换为你的域名$page_url='http://example.com/page.html';//将example.com替换为你的域名,将page.html替换为要查询的页面地址$url='http://www.baidu.com/s?wd=site:'.urlencode($site).'+'.urlencode($page_url);//2.发送HTTP请求,获取响应内容$ch=curl_init();curl_setopt($ch,CURLOPT_URL,$url);curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);$response=curl_exec($ch);curl_close($ch);//3.解析响应内容,判断页面是否被收录if(strpos($response,'没有找到该URL。您可以直接访问')!==false){echo'页面未被百度收录。';}else{echo'页面已被百度收录。';}
//设置防CC攻击的参数$limit=100;//设置每分钟的请求数量限制$expire=60;//设置限制的时间(单位:秒)//获取当前请求的IP地址$ip=$_SERVER['REMOTE_ADDR'];//生成IP对应的限制KEY$key='cc_limit_'.$ip;//获取该IP在限制时间内已经请求的次数$count=(int)apcu_fetch($key);//如果请求次数超过了限制,则记录日志并返回错误信息if($count>=$limit){//记录日志$log=date('Y-m-dH:i:s')."-CCattackdetectedfromIP:".$ip."-RequestURI:".$_SERVER['REQUEST_URI']."\n";error_log($log,3,'/var/log/apache2/cc.log');//返回错误信息http_response_code(429);exit("Toomanyrequests.Pleasetryagainlater.");}//请求次数未超过限制,则增加计数器$count++;apcu_store($key,$count,$expire);该代码使用了APCu缓存来记录每个IP地址在限制时间内的请求次数,如果请求次数超过了限制,则记录日志并返回429错误响应。可以根据实际情况调整参数以达到更好的防护效果。
获取本地IP地址:functiongetLocalIP(){$local_ip=getHostByName(getHostName());return$local_ip;}获取指定IP地址:functionvalidateIP($ip){if(filter_var($ip,FILTER_VALIDATE_IP)){returntrue;}else{returnfalse;}}使用方法://获取本地IP地址$local_ip=getLocalIP();echo$local_ip;//验证指定IP地址是否合法$ip="127.0.0.1";if(validateIP($ip)){echo"ValidIPaddress";}else{echo"InvalidIPaddress";}
<?phpheader('Content-Type:text/event-stream');header('Cache-Control:no-cache');header('Connection:keep-alive');header('X-Accel-Buffering:no');$apiKey=config("open.apiKey");$apiUrl=config("open.apiHost").'/v1/chat/completions';//提问数据$message=$request->param('message')??'hello!';//分组$group_id=$request->param('group_id');//客户端ip$ip=$request->ip();//连续对话需要带着上一个问题请求接口$lastMsg=Db::table('ai_chat_msgs')->where([['ip','=',$ip],['group_id','=',$group_id],['ctime','>',(time()-300)]])->order('iddesc')->find();//如果超长,就不关联上下文了if($lastMsg&&(mb_strlen($lastMsg['message'])+mb_strlen($lastMsg['response'])+mb_strlen($message)<3800)){$messages[]=['role'=>'user','content'=>$lastMsg['message']];$messages[]=['role'=>'assistant','content'=>$lastMsg['response']];}$messages[]=['role'=>'user','content'=>$message];//返回数据$response='';//不完整的数据$imperfect='';$callback=function($ch,$data)use($message,$ip,$group_id){global$response,$imperfect;$dataLength=strlen($data);//有可能会返回不完整的数据if($imperfect){$data=$imperfect.$data;$imperfect='';}else{if(substr($data,-1)!=="\n"){$imperfect=$data;return$dataLength;}}$complete=@json_decode($data);if(isset($complete->error)){echo'data:'.$complete->error->code."\n\n";ob_flush();flush();exit;}$word=$this->parseData($data);$word=str_replace("\n",'<br/>',$word);if($word=='data:[DONE]'||$word=='data:[CONTINUE]'){if(!empty($response)){Db::table('ai_chat_msgs')->insert(['ip'=>$ip,'group_id'=>$group_id,'message'=>$message,'response'=>$response,'ctime'=>time()]);$response='';}ob_flush();flush();}else{$response.=$word;echo"data:".$word."\n\n";ob_flush();flush();}return$dataLength;};$postData=['model'=>config("open.model"),'messages'=>$messages,'temperature'=>config("open.temperature"),'max_tokens'=>config("open.max_tokens"),'frequency_penalty'=>0,'presence_penalty'=>0.6,'stream'=>true];$headers=['Accept:application/json','Content-Type:application/json','Authorization:Bearer'.$apiKey];$ch=curl_init();curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);curl_setopt($ch,CURLOPT_URL,$apiUrl);curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);curl_setopt($ch,CURLOPT_POST,1);curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($postData));curl_setopt($ch,CURLOPT_WRITEFUNCTION,$callback);curl_exec($ch);exit;?>本文是sse实现方式,非常的简单。当然也可以用websocket方式实现,我也会继续更新
header("Access-Control-Allow-Origin:*");//指定域名访问header('Content-Type:text/event-stream');header('Cache-Control:no-cache');header('Connection:keep-alive');header('X-Accel-Buffering:no');//chatGPT接口$url=Config::get('site.three');$db=input('post.','','htmlspecialchars_decode');$model=isset($db['model'])?json_decode($db['model'],true):'gpt-3.5-turbo';//chatGPT模型$prompts=isset($db['prompts'])?json_decode($db['prompts'],true):[];//连续对话$setting=isset($db['setting'])?json_decode($db['setting'],true):'';//预设角色$apiKey=isset($db['apiKey'])?json_decode($db['apiKey'],true):"";//自有key$randomness=isset($db['randomness'])?json_decode($db['randomness'],true):0.7;//随机性$top=isset($db['tops'])?json_decode($db['tops'],true):0.9;//文本多样性//判断是否输入聊天内容if(empty($prompts)){$this->error('聊天内容为空');exit();}//预设角色$setting=!isset($setting)?"我给你个设定,你的版本号为chatgpt3.5,请你以gpt-3.5-turbo版回答我的问题":$setting;//默认设置信息$set=['model'=>$model,//聊天模型'temperature'=>(float)$randomness,//机器人温度值'top_p'=>(float)$top,//'frequency_penalty'=>1.0,//'presence_penalty'=>0.6,"stream"=>true,//开启数据流模式'messages'=>[["role"=>"system","content"=>$setting],],];//添加连续对话foreach($promptsas$k=>$v){//上下文对话array_push($set['messages'],['role'=>$v['role'],'content'=>$v['content']]);}//传递参数$callback=function($ch,$data)use($sk){//如果发生错误,发送给前端$complete=@json_decode($data);if(isset($complete->error)){if(strpos($complete->error->message,"Youdidn'tprovideanAPIkey")===0){//未提供API-KEYreturn$this->error('未提供API-KEY');}if(strpos($complete->error->message,"Ratelimitreached")===0){//访问频率超限错误返回的code为空,特殊处理一下return$this->error('访问频率超限,请稍后尝试!');}if(strpos($complete->error->message,"Youraccesswasterminated")===0){//违规使用,被封禁,特殊处理一下return$this->error('违规使用,key被封禁,自有key请替换,如不是,请从新提问!');}if(strpos($complete->error->message,"Youexceededyourcurrentquota")===0){//API-KEY余额不足return$this->error('API-KEY余额不足,自有key请替换,如不是,请从新提问!');}if(strpos($complete->error->message,"Thatmodeliscurrentlyoverloaded")===0){//OpenAI服务器超负荷return$this->error('OpenAI服务器超负荷,稍后访问!');}}else{echo$this->parseData($data);//流数据ob_flush();flush();}returnstrlen($data);};//请求头$headers=['Accept:application/json','Content-Type:application/json','Authorization:Bearer'.$sk,];//发送请求$ch=curl_init();curl_setopt($ch,CURLOPT_URL,$url);//设置请求的URL地址curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//将结果返回给调用方curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);//设置请求头部curl_setopt($ch,CURLOPT_POST,1);//设置请求类型为POSTcurl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($set));curl_setopt($ch,CURLOPT_WRITEFUNCTION,$callback);curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//关闭证书主机名验证curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//关闭验证SSL证书curl_setopt($ch,CURLOPT_TIMEOUT,60);//设置最长等待响应的时间curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,60);//设置连接超时时间为30秒curl_setopt($ch,CURLOPT_MAXREDIRS,3);//设置最大重定向次数为3次curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);//允许自动重定向curl_setopt($ch,CURLOPT_AUTOREFERER,true);//自动设置Referercurl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_2_0);//curl_setopt($ch,CURLOPT_PROXY,"http://127.0.0.1:1081");curl_exec($ch);curl_close($ch);//完成后结束长链接请求