php的curl实现get和post的代码
程序员文章站
2022-04-09 08:29:34
curl 支持ssl证书、http post、http put 、ftp 上传,kerberos、基于htt格式的上传、代理、cookie、用户+口令证明、文件传送恢复、h...
curl 支持ssl证书、http post、http put 、ftp 上传,kerberos、基于htt格式的上传、代理、cookie、用户+口令证明、文件传送恢复、http代理通道就最常用的来说,是基于http的get和post方法。
代码实现:
1、http的get实现
$ch = curl_init("//www.jb51.net/") ;
curl_setopt($ch, curlopt_returntransfer, true) ;
curl_setopt($ch, curlopt_binarytransfer, true) ;
$output = curl_exec($ch) ;
$fh = fopen("out.html", 'w') ;
fwrite($fh, $output) ;
fclose($fh) ;
2、http的post实现
//extract data from the post
extract($_post) ;
//set post variables
$url = '//www.jb51.net/get-post.php' ;
$fields = array(
'lname'=>urlencode($last_name) ,
'fname'=>urlencode($first_name) ,
'title'=>urlencode($title) ,
'company'=>urlencode($institution) ,
'age'=>urlencode($age) ,
'email'=>urlencode($email) ,
'phone'=>urlencode($phone)
);
//url-ify the data for the post
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&' ; }
rtrim($fields_string ,'&') ;
//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)) ;
curl_setopt($ch, curlopt_postfields,$fields_string) ;
//execute post
$result = curl_exec($ch) ;
//close connection
curl_close($ch) ;
代码实现:
1、http的get实现
复制代码 代码如下:
$ch = curl_init("//www.jb51.net/") ;
curl_setopt($ch, curlopt_returntransfer, true) ;
curl_setopt($ch, curlopt_binarytransfer, true) ;
$output = curl_exec($ch) ;
$fh = fopen("out.html", 'w') ;
fwrite($fh, $output) ;
fclose($fh) ;
2、http的post实现
复制代码 代码如下:
//extract data from the post
extract($_post) ;
//set post variables
$url = '//www.jb51.net/get-post.php' ;
$fields = array(
'lname'=>urlencode($last_name) ,
'fname'=>urlencode($first_name) ,
'title'=>urlencode($title) ,
'company'=>urlencode($institution) ,
'age'=>urlencode($age) ,
'email'=>urlencode($email) ,
'phone'=>urlencode($phone)
);
//url-ify the data for the post
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&' ; }
rtrim($fields_string ,'&') ;
//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)) ;
curl_setopt($ch, curlopt_postfields,$fields_string) ;
//execute post
$result = curl_exec($ch) ;
//close connection
curl_close($ch) ;
上一篇: Servlet(生命周期)
下一篇: 百度爱采购六大权益