A. php socket重連機制實現
";
}
fclose($conn);
}
function WriteData($conn,$host,$data)
{
$header = "POST /test.php HTTP/1.1\r\n";
$header.= "Host : {$host}\r\n";
$header.= "Content-type: application/x-www-form-urlencoded\r\n";
$header.= "Content-Length:".strlen($data)."\r\n";
//Keep-Alive是關鍵
$header.= "Connection: Keep-Alive\r\n\r\n";
$header.= "{$data}\r\n\r\n";
fwrite($conn,$header);
//取結果
//$result = '';
//while(!feof($conn))
//{
// $result .= fgets($conn,128);
//}
//return $result;
}
Post('127.0.0.1',80);
?>
B. php 如何發送http請求!
第一種實現方式:實用socket編程,通常我們實用fsockopen這個函數來創建一個socket連接,用fputs來發送一個請求
第二種實現方式:實用php的curl擴展,我們使用curl_init()來初始化一個連接,然後設置一堆的curl_setopt()的東西來設置url,post的數據等等,最後我們使用curl_exec()來實現請求。
第三種方式就是: 實用file_get_contents函數,其實我們平時抓取一個網頁可能只實用它的第一個參數,其實它的第三個參數就有數據了
C. java 怎麼實現HTTP的POST方式通訊,以及HTTPS方式傳遞
雖然在 JDK 的 java.net 包中已經提供了訪問 HTTP 協議的基本功能,但是對於大部分應用程序來說,JDK
庫本身提供的功能還不夠豐富和靈活。HttpClient 是 Apache Jakarta Common
下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,並且它支持 HTTP 協議最新的版本和建議。以下是簡單的post例子:
String url = "http://www.newsmth.net/bbslogin2.php";
PostMethod postMethod = new PostMethod(url);
// 填入各個表單域的值
NameValuePair[] data = { new NameValuePair("id", "youUserName"),
new NameValuePair("passwd", "yourPwd") };
// 將表單的值放入postMethod中
postMethod.setRequestBody(data);
// 執行postMethod
int statusCode = httpClient.executeMethod(postMethod);
// HttpClient對於要求接受後繼服務的請求,象POST和PUT等不能自動處理轉發
// 301或者302
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
// 從頭中取出轉向的地址
Header locationHeader = postMethod.getResponseHeader("location");
String location = null;
if (locationHeader != null) {
location = locationHeader.getValue();
System.out.println("The page was redirected to:" + location);
} else {
System.err.println("Location field value is null.");
}
return;
}
D. php的curl和socket的區別
首先說下啥是socket:
PHP使用berkely的socket庫來創建他的連接,socket是一個數據結果,你可以通過這個socket來開啟伺服器和客戶端的會話。伺服器端一直處於監聽狀態,當一個客戶端連接伺服器,他就打開伺服器端正在監聽的一個埠進行會話。這時伺服器端接收客戶端的連接請求,那麼就進行一次循環。現在這個客戶端就能夠發送信息到伺服器,伺服器也可以發送信息給客戶端。
產生一個socket你一共需要三個變數:
1、一個協議
2、一個socket類型
3、一個公共協議類型
以下是對這三個變數的詳細解釋,大概了解下吧(但願你能記得住偷笑)
協議:產生一個socket有三個協議供選擇:
1、AF_INET 這個是使用比較廣泛的產生socket的協議,使用tcp或者udp協議傳輸,使用ipv4地址
2、AF_INET6 顯而易見哈,同上,不同的是使用ipv6地址
3、AF_UNIX 使用在unix或者linux機器上,這個很少使用,僅在伺服器端和客戶端均為unix或者linux系統上使用。
socket類型:
1、SOCK_STREAM 這個協議是按照順序的、可靠的、數據完整的基於位元組流的連接。這是一個使用最多的socket類型,這個socket是使用TCP來進行傳輸。
2、SOCK_DGRAM 這個協議是無連接的、固定長度的傳輸調用。該協議是不可靠的,使用UDP來進行它的連接。
3、SOCK_SEQPACKET 這個協議是雙線路的、可靠的連接,發送固定長度的數據包進行傳輸。必須把這個包完整的接受才能進行讀取。
4、SOCK_RAW 這個socket類型提供單一的網路訪問,這個socket類型使用ICMP公共協議。(ping、traceroute使用該協議)
5、SOCK_RDM 這個類型是很少使用的,在大部分的操作系統上沒有實現,它是提供給數據鏈路層使用,不保證數據包的順序
公共協議類型:
1、ICMP (Internet Control Message Protocol)互聯網控制報文協議,主要用在網關和主機上,用來檢測網路狀況和報告錯誤信息
2、TCP (Transmission Control Protocol) 傳輸控制協議,他是使用最廣泛的協議,他能夠保證數據包到達接收者那裡,如果中途出現錯誤,那麼此協議從新發送數據包。
3、UDP (User Datagram Protocol)用戶數據包協議,他是無連接的,不可靠的數據傳輸協議。
好啦,你現在知道了產生一個socke需要三個元素,那麼在php中socket_create()就需要三個參數,一個協議,一個socket類型,一個公共協議。如果創建成功,socket_create()返回一個socket資源類型,如果不成功,嘿嘿,那你會收到一個false.
CURL
cURL 是利用URL語法規定來傳輸文件和數據的工具。他支持HTTP、FTP、TELNET。
為啥要使用cURL呢?
因為,如果我們有時候想靈活的獲取網頁上的內容,例如處理coockies、驗證、表單提交、文件上傳等等等等。那麼你就需要用到cURL.據說php有著功能強大的cURL庫(因為偶也說不清強大在哪裡啦,所以用了「據說」大笑)。
php使用cURL的選項基本步驟如下:
1、初始化
2、參數設置
3、頁面內容獲取或者操作
4、釋放句柄
看看下面這個簡單的例子吧。
[php] view plain
<?php
//初始化curl
$ch = curl_init ();
/*
* 設置curl
* php手冊對於curl_setopt的解釋為:設置對於curl傳輸的操作
* curl_setopt有三個參數:資源(一般為你建立的curl句柄)、操作(你將對這個句柄作何操作)、參數(對於這個操作你給出的參數)
*/
//例如你想對網路進行某些操作
curl_setopt ( $ch, CURLOPT_URL, "http://www..com");
//現在看來你要向網路post數據
curl_setopt ( $ch, CURLOPT_POST, 1 );
/*給出了要post的數據:$post_string,post的數據可以是一個文件,
*那麼你需要以@加上文件的全路徑給出,或者你要post一些數據,
*那麼你可以按照數組形式給出,或者按照字元串給出,
*如果你想按照字元串形式給出,請把字元串urlencode,嘿嘿
*/
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_string );
/*
*把curl操作的結果以字元串形式 從curl_exec ()返回,而不是直接就輸出了
*/
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
//得到操作返回結果
$result = curl_exec ( $ch );
//關閉curl句柄
curl_close ( $ch );
?>
因為php的curl有很多操作,要都記住估計很困難,反正偶記不住啦,說些大家可能用的上的吧。大笑
獲取伺服器的一些信息
[php] view plain
<?php
//初始化curl
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, "http://www..com");
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_exec($ch);
$info = curl_getinfo($ch);
var_mp($info);
?>
通過上面的例子,你將會獲得如下信息:
「url」 //資源網路地址
「content_type」 //內容編碼
「http_code」 //HTTP狀態碼
「header_size」 //header的大小
「request_size」 //請求的大小
「filetime」 //文件創建時間
「ssl_verify_result」 //SSL驗證結果
「redirect_count」 //跳轉技術
「total_time」 //總耗時
「namelookup_time」 //DNS查詢耗時
「connect_time」 //等待連接耗時
「pretransfer_time」 //傳輸前准備耗時
「size_upload」 //上傳數據的大小
「size_download」 //下載數據的大小
「speed_download」 //下載速度
「speed_upload」 //上傳速度
「download_content_length」//下載內容的長度
「upload_content_length」 //上傳內容的長度
「starttransfer_time」 //開始傳輸的時間
「redirect_time」//重定向耗時
E. PHP如何獲取需要登陸後才能看到的網頁HTML代碼
實際上是個模擬登陸的問題,需要寫個登陸模塊,解決兩個問題:
1,請求登陸並刷新的函數部分:
<?php
/*****************函數部分**************************/
/*獲取指定網頁的內容
$url為網頁地址
*/
function getcontent($url){
if($open=file($url)){
$count=count($open);
for($i=0;$i<$count;$i++)
{
$theget.=$open[$i];
}
}else{
die('請求過多,超時,請刷新');
}
return $theget;
}
?>
2,偷取程序部分,也分兩部分,
1),PHP與XML不同之處是需要特殊的調用才能支持COOKIE.或者記錄SessionID(後面有說明程序)
php代碼如下
<?PHP
//登陸並保存COOKIE
$f = fsockopen("www.url.net",80);
$cmd = <<<EOT
GET /test/login.php?name=test&password=test HTTP/1.0
EOT;
fputs($f,$cmd);
$result = '';
$cookie = '';
$location = '';
while($line = fgets($f))
{
$result .= $line;
//取得location跟setCookie頭HTTP頭信息
$tmp = explode(":",$line);
if($tmp[0]=="Set-Cookie")
$cookie .= $tmp[1];
if($tmp[0]=="Location")
$location = $tmp[1];
}
fclose($f);
2),獲取頁面
//下面訪問你要訪問的頁面(這部分也可以參考下面的核心常式)
$f = fsockopen("www.url.net",80);l
//下面的cookie就是發送前頁保存下的的cookie
$cmd = <<<EOT
GET /test/test.php HTTP/1.0
cookie:$cookie
EOT;
fputs($f,$cmd);
while($line = fgets($f))
{
echo $line;
}
fclose($f);
?>
核心常式就是fsockopen();
不妨再給段代碼你瞧瞧:
--------------------------------------------------------------------------------
function posttohost($url, $data)
{
$url = parse_url($url);
if (!$url) return "couldn't parse url";
if (!isset($url['port'])) { $url['port'] = ""; }
if (!isset($url['query'])) { $url['query'] = ""; }
$encoded = "";
while (list($k,$v) = each($data))
{
$encoded .= ($encoded ? "&" : "");
$encoded .= rawurlencode($k)."=".rawurlencode($v);
}
$fp = fsockopen($url['host'], $url['port'] ? $url['port'] : 80);
if (!$fp) return "Failed to open socket to $url[host]";
fputs($fp, sprintf("POST %s%s%s HTTP/1.0", $url['path'], $url['query'] ? "?" : "", $url['query']));
fputs($fp, "Host: $url[host]");
fputs($fp, "Content-type: application/x-www-form-urlencoded");
fputs($fp, "Content-length: " . strlen($encoded) . "");
fputs($fp, "Connection: close");
fputs($fp, "$encoded");
$line = fgets($fp,1024);
if (!eregi("^HTTP/1\\.. 200", $line)) return $line ;
$results = ""; $inheader = 1;
while(!feof($fp))
{
$line = fgets($fp,1024);
if ($inheader && ($line == "" || $line == "\r")) {
$inheader = 0;
}
elseif (!$inheader) {
$results .= $line;
}
}
fclose($fp);
return $results;
}
$data=array();
$data["msg"]="HELLO THIS IS TEST MSG";
$data["Type"]="TEXT";
echo posttohost("http://url/xxx", $data);
應該說明白了吧?
另外登陸部分還有一種簡單方法是把SessionID保存下來
源代碼:
<?php
/*
* 得到網頁內容
* 參數:$host [in] string
* 主機名稱(例如: www.url.com.cn)
* 參數:$method [in] string
* 提交方法:POST, GET, HEAD ... 並加上相應的參數( 具體語法參見 RFC1945,RFC2068 )
* 參數:$str [in] string
* 提交的內容
* 參數:$sessid [in] string
* PHP的SESSIONID
*
* @返回 網頁內容 string
*/
function GetWebContent($host, $method, $str, $sessid = '')
{
$ip = gethostbyname($host);
$fp = fsockopen($ip, 80);
if (!$fp) return;
fputs($fp, "$method\r\n");
fputs($fp, "Host: $host\r\n");
if (!empty($sessid))
{
fputs($fp, "Cookie: PHPSESSID=$sessid; path=/;\r\n");
}
if ( substr(trim($method),0, 4) == "POST")
{
fputs($fp, "Content-Length: ". strlen($str) . "\r\n"); // 別忘了指定長度
}
fputs($fp, "Content-Type: application/x-www-form-urlencoded\r\n\r\n");
if ( substr(trim($method),0, 4) == "POST")
{
fputs($fp, $str."\r\n");
}
while(!feof($fp))
{
$response .= fgets($fp, 1024);
}
$hlen = strpos($response,"\r\n\r\n"); // LINUX下是 "\n\n"
$header = substr($response, 0, $hlen);
$entity = substr($response, $hlen + 4);
if ( preg_match('/PHPSESSID=([0-9a-z]+);/i', $header, $matches))
{
$a['sessid'] = $matches[1];
}
if ( preg_match('/Location: ([0-9a-z\_\?\=\&\#\.]+)/i', $header, $matches))
{
$a['location'] = $matches[1];
}
$a['content'] = $entity;
fclose($fp);
return $a;
}
/* 構造用戶名,密碼字元串 */
$str = ("username=test&password=test");
$response = GetWebContent("localhost","POST /login.php HTTP/1.0", $str);
echo $response['location'].$response['content']."<br>";
echo $response['sessid']."<br>";
if ( preg_match('/error\.php/i',$response['location']))
{
echo "登陸失敗<br>";
} else {
echo "登陸成功<br>";
// 不可以訪問user.php,因為不帶sessid參數
$response = GetWebContent("localhost","GET /user.php HTTP/1.0", '', '');
echo $response['location']."<br>"; // 結果:error.php?errcode=2
// 可以訪問user.php
$response = GetWebContent("localhost","GET /user.php HTTP/1.0", '', $response['sessid']);
echo $response['location']."<br>"; // 結果:user.php
}
?>
F. php實現httpRequest的方法
這篇文章主要介紹了php實現httpRequest的方法,涉及php操作http的技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了php實現httpRequest的方法。分享給大家供大家參考。具體如下:
想從學校圖書館的網站上抓取數據處理之後在返回給瀏覽器,試了不少方法。首先試了http_request(),但是這個學院pecl_http支持,後來又試了網上流傳甚廣的class
HttpRequest,可能是我不會使用,也失敗了。後來看到了函數httpRequest($url,
$post='',
$method='GET',
$limit=0,
$returnHeader=FALSE,
$cookie='',
$bysocket=FALSE,
$ip='',
$timeout=15,
$block=TRUE),用它成功了,因此貼出來分享一下。函數代碼如下:
代碼如下:
<?php
/**
*
Respose
A
Http
Request
*
*
@param
string
$url
*
@param
array
$post
*
@param
string
$method
*
@param
bool
$returnHeader
*
@param
string
$cookie
*
@param
bool
$bysocket
*
@param
string
$ip
*
@param
integer
$timeout
*
@param
bool
$block
*
@return
string
Response
*/
function
httpRequest($url,$post='',$method='GET',$limit=0,$returnHeader=FALSE,$cookie='',$bysocket=FALSE,$ip='',$timeout=15,$block=TRUE)
{
$return
=
'';
$matches
=
parse_url($url);
!isset($matches['host'])
&&
$matches['host']
=
'';
!isset($matches['path'])
&&
$matches['path']
=
'';
!isset($matches['query'])
&&
$matches['query']
=
'';
!isset($matches['port'])
&&
$matches['port']
=
'';
$host
=
$matches['host'];
$path
=
$matches['path']
?
$matches['path'].($matches['query']
?
'?'.$matches['query']
:
'')
:
'/';
$port
=
!empty($matches['port'])
?
$matches['port']
:
80;
if(strtolower($method)
==
'post')
{
$post
=
(is_array($post)
and
!empty($post))
?
http_build_query($post)
:
$post;
$out
=
"POST
$path
HTTP/1.0rn";
$out
.=
"Accept:
*/*rn";
//$out
.=
"Referer:
$boarrlrn";
$out
.=
"Accept-Language:
zh-cnrn";
$out
.=
"Content-Type:
application/x-www-form-urlencodedrn";
$out
.=
"User-Agent:
$_SERVER[HTTP_USER_AGENT]rn";
$out
.=
"Host:
$hostrn";
$out
.=
'Content-Length:
'.strlen($post)."rn";
$out
.=
"Connection:
Closern";
$out
.=
"Cache-Control:
no-cachern";
$out
.=
"Cookie:
$cookiernrn";
$out
.=
$post;
}
else
{
$out
=
"GET
$path
HTTP/1.0rn";
$out
.=
"Accept:
*/*rn";
//$out
.=
"Referer:
$boarrlrn";
$out
.=
"Accept-Language:
zh-cnrn";
$out
.=
"User-Agent:
$_SERVER[HTTP_USER_AGENT]rn";
$out
.=
"Host:
$hostrn";
$out
.=
"Connection:
Closern";
$out
.=
"Cookie:
$cookiernrn";
}
$fp
=
fsockopen(($ip
?
$ip
:
$host),
$port,
$errno,
$errstr,
$timeout);
if(!$fp)
return
'';
else
{
$header
=
$content
=
'';
stream_set_blocking($fp,
$block);
stream_set_timeout($fp,
$timeout);
fwrite($fp,
$out);
$status
=
stream_get_meta_data($fp);
if(!$status['timed_out'])
{//未超時
while
(!feof($fp))
{
$header
.=
$h
=
fgets($fp);
if($h
&&
($h
==
"rn"
||
$h
==
"n"))
break;
}
$stop
=
false;
while(!feof($fp)
&&
!$stop)
{
$data
=
fread($fp,
($limit
==
0
||
$limit
>
8192
?
8192
:
$limit));
$content
.=
$data;
if($limit)
{
$limit
-=
strlen($data);
$stop
=
$limit
<=
0;
}
}
}
fclose($fp);
return
$returnHeader
?
array($header,$content)
:
$content;
}
}
?>
調用也很簡單的。簡單的例子:
代碼如下:
echo
httpRequest('http://www..com');
希望本文所述對大家的php程序設計有所幫助。
G. PHP如何不用表單直接向其他地址POST數據
用sestion吧。。。用法和POST一樣,但是不用經過表單,而且是全局可以調用的。。
H. 如何用PHP定義socket的包頭
$info["path"] = '/index.html';
$info["host"] = '127.0.0.1';
$info["port"]=80;
$data_string= "name=peter";
這個是發送請求,重新定義了http頭部,具體信息在函數里修改就可以了。
echo url_post($info, $data_string);
function url_post($info, $data_string){
$request = '';
$request.="POST ".$info["path"]." HTTP/1.1\n";
$request.="Host: ".$info["host"]."\n";
//$request.="Referer: $referrer\n";
//$request.="Content-type: application/x-www-form-urlencoded\n";
$request.="Content-length: ".strlen($data_string)."\n";
$request.="Connection: close\n";
$request.="\n";
$request.=$data_string."\n";
//echo $request;
$fp = fsockopen($info["host"],$info["port"]);
fputs($fp, $request);
$result = '';
while(!feof($fp)) {
$result .= fgets($fp, 128);
}
fclose($fp);
return $result;
}
I. 怎麼用PHP發送POST請求
PHP發送POST請求的三種方式
classRequest{
publicstaticfunctionpost($url,$post_data='',$timeout=5){//curl
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
if($post_data!=''){
curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
curl_setopt($ch,CURLOPT_HEADER,false);
$file_contents=curl_exec($ch);
curl_close($ch);
return$file_contents;
}
publicstaticfunctionpost2($url,$data){//file_get_content$postdata=http_build_query(
$data
);$opts=array('http'=>
array(
'method'=>'POST',
'header'=>'Content-type:application/x-www-form-urlencoded',
'content'=>$postdata
)
);$context=stream_context_create($opts);
$result=file_get_contents($url,false,$context);
return$result;
}
publicstaticfunctionpost3($host,$path,$query,$others=''){//fsocket
$post="POST$pathHTTP/1.1 Host:$host ";
$post.="Content-type:application/x-www-form-";
$post.="urlencoded ${others}";
$post.="User-Agent:Mozilla4.0 Content-length:";
$post.=strlen($query)." Connection:close $query";
$h=fsockopen($host,80);
fwrite($h,$post);
for($a=0,$r='';!$a;){
$b=fread($h,8192);
$r.=$b;
$a=(($b=='')?1:0);
}
fclose($h);
return$r;
}
}
http://www.oschina.net/code/snippet_729516_33065
J. php的socket調用可以實現查天氣嗎
本文分享下,php調用yahoo與sina的天氣api,實現實時顯示天氣預報的代碼,有興趣的朋友研究下吧。
yahoo 天氣預報
地址 http://developer.yahoo.com/weather/
代碼:
復制代碼代碼示例:
<?php
header ( 'Content-Type: text/html; charset = utf-8' );
class weather {
static $url = 'http://xml.weather.yahoo.com/forecastrss?u=c&w=';
static $city = 'Beijing'; //默認城市北京 這里要注意的是 city 要填拼音 我試過用中文有好幾個地區都調用不到
static $weatherXML = '';
static $woeid_file = "woeid";
static $file_path = "data/";
/**
* 獲得遠程xml並緩存到本地
*/
static public function getXML($city = null) {
if ($city != null){
self::$city = $city;
}
self::$weatherXML = self::$file_path . md5(self::$city) . '-weather.xml';
if (file_exists( self::$weatherXML )) {
$fileTime = filemtime ( self::$weatherXML );
$stater = time () - $fileTime - 60 * 60 * 2;
if ($stater > 0) {
return true;
}
}
//獲取woeid
$woeid = self::getWOEID();
self::$url = self::$url . $woeid[0];
//獲取當天 天氣
$XML = self::vget(self::$url);
//保存當天 天氣到文件
self::cacheXML($XML);
self::analysisXML($XML);
}
static public function analysisXML($simple) {
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
//本周天氣
$weekindex = $index['YWEATHER:FORECAST'];
$week = array();
foreach($weekindex as $k=>$v){
$week[$k] = $vals[$v]['attributes'];
}
unset($index);
unset($vals);
print_r($week);
/*
<yweather:forecast day="Wed" date="18 Sep 2013" low="20" high="32" text="Sunny" code="32"/>
* day 星期
* date 日期
* low 最低溫度
* high 最高溫度
* test 天氣狀態
* code 天氣圖標
*/
}
/*
* 取得地區WOEID碼
*/
static private function getWOEID(){
static $woeid = array();
if(isset($woeid[self::$city])){
return $woeid[self::$city];
}
if (file_exists( self::$file_path . self::$woeid_file )) {
$woeidSTR = file_get_contents(self::$file_path . self::$woeid_file);
$woeid = json_decode($woeidSTR , true);
if(isset($woeid[self::$city])){
return $woeid[self::$city];
}
}
$geoPlaces = "http://query.yahooapis.com/v1/public/yql?q=select%20woeid%20from%20geo.places%20where%20text='".self::$city."%20CH'";
$XML = simplexml_load_file( $geoPlaces );
if(isset($XML->results->place[0])){
$rs = $woeid[self::$city] = $XML->results->place[0]->woeid;
//保存到文件
$woeidSTR = json_encode($woeid);
file_put_contents(self::$file_path . self::$woeid_file, $woeidSTR);
return $rs;
}else{
//如果找不到城市 woeid 默認城市就改為 北京
self::$city = "Beijing";
return self::getWOEID();
}
}
/**
* 創建xml緩存
* @param $contents 要緩存的內容
*/
static private function cacheXML($contents) {
$contents = str_ireplace ( '<?xml version="1.0"?>', "<?xml version=\"1.0\"?> \n", $contents );
$contents = mb_convert_encoding ( $contents, 'utf-8', 'gbk' );
file_put_contents ( self::$weatherXML, $contents ) or die ( '沒有寫許可權' );
}
/**
* 模擬獲取內容函數
* @param type $url
* @return type
*/
static private function vget($url) {
$user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)";
$curl = curl_init (); // 啟動一個CURL會話
curl_setopt ( $curl, CURLOPT_URL, $url ); // 要訪問的地址
curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, 0 ); // 對認證證書來源的檢查
curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, 1 ); // 從證書中檢查SSL加密演算法是否存在
curl_setopt ( $curl, CURLOPT_USERAGENT, $user_agent ); // 模擬用戶使用的瀏覽器
@curl_setopt ( $curl, CURLOPT_FOLLOWLOCATION, 1 ); // 使用自動跳轉
curl_setopt ( $curl, CURLOPT_AUTOREFERER, 1 ); // 自動設置Referer
curl_setopt ( $curl, CURLOPT_HTTPGET, 1 ); // 發送一個常規的Post請求
curl_setopt ( $curl, CURLOPT_TIMEOUT, 120 ); // 設置超時限制防止死循環
curl_setopt ( $curl, CURLOPT_HEADER, 0 ); // 顯示返回的Header區域內容
curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 ); // 獲取的信息以文件流的形式返回
$tmpInfo = curl_exec ( $curl ); // 執行操作
if (curl_errno ( $curl )) {
curl_close ( $curl ); // 關閉CURL會話
die('Errno' . curl_error ( $curl )) ;
}
curl_close ( $curl ); // 關閉CURL會話
return $tmpInfo; // 返回數據
}
}
weather::getXML("Changsha");