请教用Curl 在php 里面模拟表单提交 文本+文件的写法
1个回答
展开全部
public function curl($url, $postFields = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($this->readTimeout) {
curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
}
if ($this->connectTimeout) {
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
}
//https 请求
if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
if (is_array($postFields) && 0 < count($postFields))
{
$postBodyString = "";
$postMultipart = false;
foreach ($postFields as $k => $v)
{
if("@" != substr($v, 0, 1))//判断是不是文件上传
{
$postBodyString .= "$k=" . urlencode($v) . "&";
}
else//文件上传用multipart/form-data,否则用www-form-urlencoded
{
$postMultipart = true;
}
}
unset($k, $v);
curl_setopt($ch, CURLOPT_POST, true);
if ($postMultipart)
{
foreach ($postFields as $k => $v){
if ("@" == substr($v, 0, 1)){
$tempffile = preg_replace ('/^\@/' ,'' ,$v);
$advfield[$k] = new CURLFile($tempffile);
}else {
$advfield[$k] = $v;
}
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $advfield);
unset($k, $v, $advfield);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); //田村改
//curl_setopt($ch, CURLOPT_POSTFIELDS, ['file' => new CURLFile(realpath('image.png'))]);
}
else
{
curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1));
}
}
$reponse = curl_exec($ch);
if (curl_errno($ch))
{
throw new Exception(curl_error($ch),0);
}
else
{
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (200 !== $httpStatusCode)
{
throw new Exception($reponse,$httpStatusCode);
}
}
curl_close($ch);
return $reponse;
}
表单列表是 $postFields 传入参数
数组,如果有文件 ,就在数组的值 前面加@
已经做好的 集成类 的实现 其他类字段和方法没给出,写不下了。
但是大致的实现过程应该可以看懂了
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询