PHP的cURL庫簡介及使用示例
Jun 13, 2016 am 09:15 AMPHP的cURL庫簡介及使用示例
?這篇文章主要介紹了PHP的cURL庫簡介及使用示例,需要的朋友可以參考下
?
?
使用PHP的cURL庫可以簡單和有效地去抓網(wǎng)頁。你只需要運行一個腳本,然后分析一下你所抓取的網(wǎng)頁,然后就可以以程序的方式得到你想要的數(shù)據(jù)了。無論是你想從從一個鏈接上取部分數(shù)據(jù),或是取一個XML文件并把其導入數(shù)據(jù)庫,那怕就是簡單的獲取網(wǎng)頁內(nèi)容,cURL 是一個功能強大的PHP庫。
PHP中的CURL函數(shù)庫(Client URL Library Function)
?
?代碼如下:
curl_close — 關閉一個curl會話
curl_copy_handle — 拷貝一個curl連接資源的所有內(nèi)容和參數(shù)
curl_errno — 返回一個包含當前會話錯誤信息的數(shù)字編號
curl_error — 返回一個包含當前會話錯誤信息的字符串
curl_exec — 執(zhí)行一個curl會話
curl_getinfo — 獲取一個curl連接資源句柄的信息
curl_init — 初始化一個curl會話
curl_multi_add_handle — 向curl批處理會話中添加單獨的curl句柄資源
curl_multi_close — 關閉一個批處理句柄資源
curl_multi_exec — 解析一個curl批處理句柄
curl_multi_getcontent — 返回獲取的輸出的文本流
curl_multi_info_read — 獲取當前解析的curl的相關傳輸信息
curl_multi_init — 初始化一個curl批處理句柄資源
curl_multi_remove_handle — 移除curl批處理句柄資源中的某個句柄資源
curl_multi_select — Get all the sockets associated with the cURL extension, which can then be "selected"
curl_setopt_array — 以數(shù)組的形式為一個curl設置會話參數(shù)
curl_setopt — 為一個curl設置會話參數(shù)
curl_version — 獲取curl相關的版本信息
curl_init()函數(shù)的作用初始化一個curl會話,curl_init()函數(shù)唯一的一個參數(shù)是可選的,表示一個url地址。
curl_exec()函數(shù)的作用是執(zhí)行一個curl會話,唯一的參數(shù)是curl_init()函數(shù)返回的句柄。
curl_close()函數(shù)的作用是關閉一個curl會話,唯一的參數(shù)是curl_init()函數(shù)返回的句柄。
?
例子一: 基本例子
?
代碼如下:
﹤?php
// 初始化一個 cURL 對象
$curl = curl_init();
// 設置你需要抓取的URL
curl_setopt($curl, CURLOPT_URL, 'http://www.cmx8.cn');
// 設置header
curl_setopt($curl, CURLOPT_HEADER, 1);
// 設置cURL 參數(shù),要求結(jié)果保存到字符串中還是輸出到屏幕上。
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// 運行cURL,請求網(wǎng)頁
$data = curl_exec($curl);
// 關閉URL請求
curl_close($curl);
// 顯示獲得的數(shù)據(jù)
var_dump($data);
?>
?
例子二: POST數(shù)據(jù)
sendSMS.php,其可以接受兩個表單域,一個是電話號碼,一個是短信內(nèi)容。
?
?代碼如下:
﹤?php
$phoneNumber = '13812345678';
$message = 'This message was generated by curl and php';
$curlPost = 'pNUMBER=' . urlencode($phoneNumber) . '&MESSAGE=' . urlencode($message) . '&SUBMIT=Send';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.lxvoip.com/sendSMS.php');
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec();
curl_close($ch);
?﹥
?
例子三:使用代理服務器
?
?代碼如下:
﹤?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.cmx8.cn');
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
curl_setopt($ch, CURLOPT_PROXY, 'proxy.lxvoip.com:1080');
curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'user:password');
$data = curl_exec();
curl_close($ch);
?﹥
?
例子四: 模擬登錄
Curl 模擬登錄 discuz 程序,適合DZ7.0,將username改成你的用戶名,userpass改成你的密碼就可以了.
?
?代碼如下:
/**
* Curl 模擬登錄 discuz 程序
* 尚未實現(xiàn)開啟驗證碼的的論壇登錄功能
*/
!extension_loaded('curl') && die('The curl extension is not loaded.');
$discuz_url = 'http://www.lxvoip.com';//論壇地址
$login_url = $discuz_url .'/logging.php?action=login';//登錄頁地址
$get_url = $discuz_url .'/my.php?item=threads'; //我的帖子
$post_fields = array();
//以下兩項不需要修改
$post_fields['loginfield'] = 'username';
$post_fields['loginsubmit'] = 'true';
//用戶名和密碼,必須填寫
$post_fields['username'] = 'lxvoip';
$post_fields['password'] = '88888888';
//安全提問
$post_fields['questionid'] = 0;
$post_fields['answer'] = '';
//@todo驗證碼
$post_fields['seccodeverify'] = '';
//獲取表單FORMHASH
$ch = curl_init($login_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
curl_close($ch);
preg_match('//i', $contents, $matches);
if(!empty($matches)) {
$formhash = $matches[1];
} else {
die('Not found the forumhash.');
}
//POST數(shù)據(jù),獲取COOKIE
$cookie_file = dirname(__FILE__) . '/cookie.txt';
//$cookie_file = tempnam('/tmp');
$ch = curl_init($login_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_exec($ch);
curl_close($ch);
//帶著上面得到的COOKIE獲取需要登錄后才能查看的頁面內(nèi)容
$ch = curl_init($get_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
$contents = curl_exec($ch);
curl_close($ch);
var_dump($contents);
?>
?
以上就是本文的全部內(nèi)容了,希望大家能夠喜歡。
?

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

When encountering the problem that header('Location:...') does not work, the common reasons and solutions are as follows: 1. There is output in advance, causing the header to fail. The solution is to ensure that there is no output before the jump, including spaces, HTML or echo; 2. There is excess output or UTF-8 BOM characters in the include or require file. The file encoding should be checked and saved as "UTF-8 BOM-free"; 3. It is recommended to use ob_start() to turn on the output buffer before the jump, and cooperate with ob_end_flush() to delay the output; 4. After the jump, be sure to add exit to prevent subsequent code execution; 5. Make sure that the header() function call is before all outputs.
