Loading... ## 写在前面 很多人因为服务器空间少、带宽小等原因会选择把图片放在别的网站上然后插入自己的网站。这在节省带宽的同时也带来了一些问题,像是那些网站本身不稳定的话就会造成图片无法加载之类的,,,, 我在网上找了很多百度图床接口的源码都已经不能用了,这里找到了[教书先生](https://blog.oioweb.cn/index.php/archives/1226.html "教书先生")的一个源码,修复了无法上传后缀名为大写的图片的问题。 ## 代码 ```php <?php header('Access-Control-Allow-Origin:*'); header('Content-type:application/json; charset=utf-8'); error_reporting(0); $allowedExts = array("gif", "jpeg", "jpg", "png", "GIF", "JPEG", "JPG", "PNG"); $temp = explode(".", $_FILES["file"]["name"]); $extension = end($temp); if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 7*1024*1024) && in_array($extension, $allowedExts)) { if ($_FILES["file"]["error"] > 0) { error("文件错误"); } else { $post_data = [ "image"=>new \CURLFile(realpath($_FILES['file']['tmp_name'])), ]; $data = Curl_POST("https://graph.baidu.com/upload",$post_data); if ($data==""){ error("上传失败"); }elseif (json_decode($data)->msg!=="Success"){ error("上传失败"); }else{ $pic = "https://graph.baidu.com/resource/".json_decode($data)->data->sign.".jpg"; echo json_encode([ "code"=>1, "imgurl"=>$pic ]); } } }else { error("非法的文件格式"); } function randIp() { return mt_rand(0, 255) . '.' . mt_rand(0, 255) . '.' . mt_rand(0, 255) . '.' . mt_rand(0, 255); } function Curl_POST($url,$post_data){ $header=[ 'X-FORWARDED-FOR:'.randIp(), 'CLIENT-IP:'.randIp() ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_NOBODY, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, false); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4086.0 Safari/537.36 Edg/83.0.461.1"); // 伪造ua curl_setopt($ch, CURLOPT_HTTPHEADER,$header); curl_setopt($ch, CURLOPT_ENCODING, ''); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data); $data = curl_exec($ch); curl_close($ch); return $data; } function error($str){ exit(json_encode([ "code"=>-1, "msg"=>$str ],JSON_UNESCAPED_UNICODE)); } ``` ## 写在后面 #### 百度图床的缺点 上传图片后会将图片剪裁、压缩,还会把格式全部转为jpg #### 使用问题 关于如何使用我将会在以后的文章中更新 会包括如何调用接口,如何解决防盗链等 #### 搭建接口教程 [点这里~~](https://www.wangkai88.com/archives/74/ "点这里~~") #### 即将更新搜狗图床和阿里图床,比百度图床强千倍!!! 最后修改:2021 年 01 月 01 日 11 : 21 PM © 允许规范转载 赞赏 如果觉得我的文章对你有用,请随意赞赏 ×Close 赞赏作者 扫一扫支付 支付宝支付 微信支付