本篇文章是对PHP的curl实现get,post和cookie的方法进行了详细的分析介绍,需要的朋友参考下
类似于dreamhost这类主机服务商,是显示fopen的使用 的。使用php的curl可以实现支持FTP、FTPS、HTTP HTPPS SCP SFTP TFTP TELNET DICT FILE和LDAP。curl 支持SSL证书、HTTP POST、HTTP PUT 、FTP 上传,kerberos、基于HTT格式的上传、代理、cookie、用户+口令证明、文件传送恢复、http代理通道就最常用的来说,是基于http的 get和post方法。
代码实现:
1、http的get实现

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
echo $output = curl_exec($ch) ;
/* 写入文件 */
$fh = fopen(“out.html”, ‘w’) ;
fwrite($fh, $output) ;
fclose($fh)
;
2、http的post实现
$url = ‘http://www.domain.com/api/’ ;
$fields = array(
‘lname’=>’justcoding’ ,
‘fname’=>’phplover’ ,
‘title’=>’myapi’,
‘age’=>’27’ ,
’email’=>’[email protected]’ ,
‘phone’=>’1353777303’
);
//$post_data = implode(‘&’,$fields);
注意:post请求的参数要用get方式那样连接起来,作为字符串传递:
如:$params = ‘userId=’.$this->user_id.’&auth=’.$this->auth.’&sig=’.$this->sig
还有跨平台的请求,curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 (很重要)
//open connection
$ch = curl_init() ;
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL,$url) ;
curl_setopt($ch, CURLOPT_POST,count($fields)) ; // 启用时会发送一个常规的POST请求,类型为:application/x-www-form-urlencoded,就像表单提交的一样。
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields); // 在HTTP中的“POST”操作。如果要传送一个文件,需要一个@开头的文件名
ob_start();
curl_exec($ch);
$result = ob_get_contents() ;
ob_end_clean();
echo $result;
//close connection
curl_close($ch) ;
以上就是PHP的curl实现get,post和cookie(实例介绍)的详细内容,更多请关注gaodaima搞代码网其它相关文章!