php curl發送數據和文件


function mycurl($file, $url, $aid) {
// 如果文件名是中文名,將中文字符編碼轉換一下
$file=iconv("UTF-8","gb2312", $file);
$data = [
// 還有一種打成數據流的方法.
'pic'=>new \CURLFile($file),
'name' => 'qb',
// 自定義鹽簽
'token' => 'e10adc3949ba59abbe56e057f20f883e',
'aid' => $aid
];
// 創建一個新cURL資源
$ch = curl_init();

// 設置URL和相應的選項
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 跳過證書驗證(https)的網站無法跳過,會報錯
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳過證書驗證
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回的數據不打印

//偽造網頁來源地址,偽造來自百度的表單提交
curl_setopt($ch, CURLOPT_REFERER, "http://www.baidu.com");
curl_setopt($ch, CURLOPT_POST, 1); //表單數據,是正規的表單設置值為非0

/**
* 使用數組提供post數據時,CURL組件大概是為了兼容@filename這種上傳文件的寫法,
* 默認把content_type設為了multipart/form-data。雖然對於大多數web服務器並
沒有影響,但是還是有少部分服務器不兼容。本文得出的結論是,在沒有需要上傳文件的
情況下,盡量對post提交的數據進行http_build_query,然后發送出去,能實現更好的兼容性,更小的請求數據包。
* curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
*/
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 100); //設置curl執行超時時間最大是多少
// 抓取URL並把它傳遞給瀏覽器
$rs = curl_exec($ch);
if($rs === false) {
return 'Curl error: ' . curl_error($ch);
}
// 關閉cURL資源,並且釋放系統資源
curl_close($ch);
return $rs;
}

上面是發送文件

 

下面是接受文件

 
         
/**
* 獲取file數據
* @return array
*/
public function get_file()
{
// file 文件
$file = $_FILES;
// 其他參數
$post = $_POST;
// 接口鹽簽
$tokne = 'e10adc3949ba59abbe56e057f20f883e';

if (empty($file) || empty($post)) {
$res = ['code' => 199, 'msg' => '文件丟失!'];
echo json_encode($res);
     exit;
}

if ($post['token'] != $tokne) {
$res = ['code' => 199, 'msg' => '鑒權失敗!'];
     echo json_encode($res);
     exit;
    }

if ($file) {
$file_data = $this->file_move($file, $post['aid']);
if (!empty($file_data)) {
$res = ['code' => 200, 'msg' => '頭像上傳成功!'];
        echo json_encode($res);
        exit;
        } else {
$res = ['code' => 199, 'msg' => '頭像存儲失敗!'];
        echo json_encode($res);
        exit;
        }
}
}


/*
* * 接口獲取file類型文件直接轉存 * @param $file * @param $aid -- 用戶aid * @return array|string */ public function file_move($file, $aid) { $data = ''; foreach ($file as $image) { $name = $image['name']; $type = strtolower(substr($name, strrpos($name, '.') + 1)); $allow_type = ['jpg', 'jpeg', 'gif', 'png']; //判斷文件類型是否被允許上傳 if (!in_array($type, $allow_type)) { continue; } // 文件名 // $file_name = date('Ymd') . time() . rand(100, 999) . '.' . $type; // app_id 命名 $file_name = $aid . '.' . $type; //開始移動文件到相應的文件夾 if (move_uploaded_file($image['tmp_name'], ROOT_PATH . 'public' . DS . 'data' . DS . 'image' . DS . $file_name)) { $data = ROOT_PATH . 'public' . DS . 'data' . DS . 'image' . DS . $file_name; } } return $data; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM