php 利用 curl 连接各种服务器

来源:互联网 发布:网络揭阳广播电视大学 编辑:程序博客网 时间:2024/05/29 16:36
1.curl定义
    curl是一个利用URL语法在命令行方式下工作的文件传输工具。
    Client Url, allows you to connect and communicate to many different types of servers with     many different types of protocols. libcurl currently supports the http, https, ftp, gopher,     telnet, dict, file, and ldap protocols.
2.php安装curl    
    修改php.ini:配置好 extension_dir ,去掉 extension = php_curl.dll 前面的分号。(如果是xampp,则在apache/php.ini,不是php/php.ini文件)
    拷贝PHP目录中的libeay32.dll 和 ssleay32.dll 两个文件到 windows/system32 目录。
    重新启动Apache。
3.示例代码
<?php
$PostData = "foo=abc&bar=def"; 
$url="https://10.3.0.34/a3.php";

//init a curl session
$ch = curl_init();
// set the url
curl_setopt($ch, CURLOPT_URL, $url);

// Set your login and password for authentication
curl_setopt($ch, CURLOPT_USERPWD, 'login:pasword');
// CURLAUTH_ANY is an alias for CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//?#93;定伺服器憑證,要不要?#93;我忘了... 請自己 try 一下 
//curl_setopt($ch , CURLOPT_CAPATH, "/certificate"); 
//curl_setopt($ch , CURLOPT_CAINFO, "/certificate/server.crt");

curl_setopt($ch, CURLOPT_USERAGENT, 'Opera/9.23 (Windows NT 5.1; U; en)');

//common name and also verify that it matches the hostname provided)
curl_setopt($ch , CURLOPT_SSL_VERIFYPEER, false); 
//這行請參考 http://curl.haxx.se 的介紹 
curl_setopt($ch , CURLOPT_SSL_VERIFYHOST, 2); 
 

//不直接顯示回傳結果 ,Return the result instead of printing it
curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1); 

//post資料給指定網頁 
curl_setopt($ch , CURLOPT_POST, 1); 
curl_setopt($ch , CURLOPT_POSTFIELDS, $PostData); 

$Result = curl_exec($ch ); 

curl_close($ch ); 
参考:
1.http://blog.taragana.com/index.php/archive/how-to-use-curl-in-php-for-authentication-and-ssl-communication/
2.http://hi.baidu.com/freshcn/blog/item/88e80024ee436937c9955920.html