教学之友,学习之友。

站长教学网

当前位置: 站长教学网 > 网站编程 > PHP教程 >

PHP如何利用curl实现get,post和cookie实例 .

时间:2012-05-24 00:22来源:未知 作者:ken 点击:

curl 支持SSL证书、HTTP POST、HTTP PUT 、FTP 上传,kerberos、基于HTT格式的上传、代理、cookie、用户+口令证明、文件传送恢复、http代理通道就最常用的来说,是基于http的 get和post方法。类似于dreamhost这类主机服务商,是显示fopen的使用的。使用php的curl可以实现支持FTP、FTPS、HTTP HTPPS SCP SFTP TFTP TELNET DICT FILE和LDAP。 

代码实现:

1、http的get实现

$ch = curl_init("http://www.eduyo.com/api/index.php?test=1") ;
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实现

<?php
$url = 'http://www.eduyo.com/api/' ;
$fields = array(
               'lname'=>'justcoding' ,
               'fname'=>'phplover' ,
               'title'=>'myapi',
               'age'=>'27' ,
               'email'=>'1353777303@gmail.com' ,
               'phone'=>'1353777303'
              );
//$post_data = implode('&',$fields);

//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) ;

 

测试地址:http://www.eduyo.com/api/index.php

<?php

if($_GET['test'])
{
  print_r($_GET);
}

if($_POST)
{
 print_r($_POST);
}

  (责任编辑:ken)

TAG标签: php curl Cookie 源码 get post 实例
顶一下
(1)
100%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
注册登录:不允许匿名留言,登录后留言无需输入验证码。
栏目列表
最新内容