php curl访问https站点,最重要的就是证书问题。我遇到的问题有:证书太严格请求失败,https返回数据太长,导致看到的返回内容是乱码。
返回乱码需要指定以下字段:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
以下代码为向virmach POST提交一个优惠码:
<?php $url = "https://virmach.com/manage/cart.php?a=view"; $post_full = "token=71bc2c5cd3c069bd248f6287075a28e4e3babc63&validatepromo=true&promocode=WHTE329AUG"; $cookie = "__cfduid=d548bd8ce373dd950f6b4ce9986560c531470640677; __utma=12432051.990664983.1470640681.1470640681.1470640681.1; __utmb=12432051.3.10.1470640681; __utmz=12432051.1470640681.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmt=1; __tawkuuid=e::virmach.com::L/NqMfl7V6tqSB7qXiLnK5V1QVQzcy7Dpxogyt+aqhFGNJ79d1KGYWBFqnPAv+Ic::2; Tawk_56719ef6817c118b50f5e141=vs3.tawk.to:443::0; WHMCSeXMvUTd4giP5=8vntgorqkb2m32ov80tqclh4b7; __utmc=12432051; TawkConnectionTime=0"; $UGA = "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"; $reffer = "https://virmach.com/manage/cart.php?a=view"; function curl_post($url,$UGA,$cookie,$reffer,$post_full) { $ch = curl_init(); $headers = array(); // $cacert = getcwd() . '/cacert.pem'; $headers[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; $headers[] = "Accept-Language: q=0.8,en-US;q=0.5,en;q=0.3"; $headers[] = "Accept-Encoding: gzip, deflate"; $headers[] = "DNT: 1"; $headers[] = "Connection: keep-alive"; $headers[] = "Content-Type: application/x-www-form-urlencoded"; curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_USERAGENT, $UGA); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch,CURLOPT_COOKIE, $cookie); // curl_setopt($ch, CURLOPT_CAINFO, $cacert); curl_setopt($ch,CURLOPT_REFERER, $reffer); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT,40); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false); // curl_setopt($ch, CURLOPT_CAINFO, $cacert); // echo $cacert; curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false); curl_setopt($ch, CURLOPT_POSTFIELDS,$post_full); $datas=curl_exec($ch); // var_dump(curl_error($ch)); curl_close($ch); return $datas; } echo curl_post($url,$UGA,$cookie,$reffer,$post_full); ?>
更多参考:详解使用PHP CURL访问HTTPS