PHP多种方式发送POST请求
PHP #post2014-02-17 21:12
下面列出3种发送POST请求的方法。
001 | function post( $url , $post_data = '' , $timeout = 5){ //curl |
002 |
003 | $ch = curl_init(); |
004 |
005 | curl_setopt ( $ch , CURLOPT_URL, $url ); |
006 |
007 | curl_setopt ( $ch , CURLOPT_POST, 1); |
008 |
009 | if ( $post_data != '' ){ |
010 |
011 | curl_setopt( $ch , CURLOPT_POSTFIELDS, $post_data ); |
012 |
013 | } |
014 |
015 | curl_setopt ( $ch , CURLOPT_RETURNTRANSFER, 1); |
016 |
017 | curl_setopt ( $ch , CURLOPT_CONNECTTIMEOUT, $timeout ); |
018 |
019 | curl_setopt( $ch , CURLOPT_HEADER, false); |
020 |
021 | $file_contents = curl_exec( $ch ); |
022 |
023 | curl_close( $ch ); |
024 |
025 | return $file_contents ; |
026 |
027 | } |
028 |
029 |
030 | function post2( $url , $data ){ //file_get_content |
031 |
032 | |
033 |
034 | $postdata = http_build_query( |
035 |
036 | $data |
037 |
038 | ); |
039 |
040 | |
041 |
042 | $opts = array ( 'http' => |
043 |
044 | array ( |
045 |
046 | 'method' => 'POST' , |
047 |
048 | 'header' => 'Content-type: application/x-www-form-urlencoded' , |
049 |
050 | 'content' => $postdata |
051 |
052 | ) |
053 |
054 | ); |
055 |
056 | |
057 |
058 | $context = stream_context_create( $opts ); |
059 |
060 |
061 | $result = file_get_contents ( $url , false, $context ); |
062 |
063 | return $result ; |
064 |
065 |
066 | } |
067 |
068 |
069 | function post3( $host , $path , $query , $others = '' ){ //fsocket |
070 |
071 |
072 | $post = "POST $path HTTP/1.1\r\nHost: $host\r\n" ; |
073 |
074 | $post .= "Content-type: application/x-www-form-" ; |
075 |
076 | $post .= "urlencoded\r\n${others}" ; |
077 |
078 | $post .= "User-Agent: Mozilla 4.0 yige.org\r\nContent-length: " ; |
079 |
080 | $post .= strlen ( $query ). "\r\nConnection: close\r\n\r\n$query" ; |
081 |
082 | $h = fsockopen ( $host ,80); |
083 |
084 | fwrite( $h , $post ); |
085 |
086 | for ( $a =0, $r = '' ;! $a ;){ |
087 |
088 | $b = fread ( $h ,8192); |
089 |
090 | $r .= $b ; |
091 |
092 | $a =(( $b == '' )?1:0); |
093 |
094 | } |
095 |
096 | fclose( $h ); |
097 |
098 | return $r ; |
099 |
100 | } |
相关文章
- PHP根据日期判断星座的函数 2013/03/22
- PHP显示搜索引擎来的关键词的函数 2013/03/21
- PHP记录用户通过搜索引擎进网站的关键词代码 2013/03/21
- 错误 Class 'SoapClient' not found in PHP 解决方法 2013/02/27
- PHP根据ISBN获取图书的方法 2013/01/14
- smarty中时间格式化函数date_format 2012/12/28
- PHP防注入安全代码 2012/12/21
- eval()一个有意思的PHP函数 2012/12/21
- php的免杀小马 2012/12/21
- PHP中eval()的小技巧 2012/12/21