在php中 cURL函数有一组相关函数,它是一个非常不错的函数了,我们经常用它来模仿各种登录与采集工作,下面我来给各位介绍CURL函数入门吧。
cURL简介
cURL是一个利用URL语法规定来传输数据和文件的工具,支持很多种协议如HTTP、FTP、TELNET等。PHP也支持 cURL 库。
假如我们要获取某个网页的内容,我们可能会使用下面这几种方法:
- <?php
- // 把整个文件读入一个字符串中
- $str = file_get_contents("http://www.phpfensi.com");
- // 把整个文件读入一个数组中
- $arr = file("http://www.phpfensi.com");
- // 读入一个文件并写入到输出缓冲
- $out = readfile("http://www.phpfensi.com");
- ?>
这几种做法相当简单,但缺乏灵活性和有效的错误处理,而且他们无法完成一些高难度动作,比如处理coockies、验证、表单提交、文件上传等等。
cURL简例
下面给出一段简单的代码,从其中你可以学习到使用cURL的大概步骤,php cURL入门教程,实例代码如下:
- <?php
- header("Content-type: text/html; charset=utf-8");
- // 1. 初始化
- $ch = curl_init();
- // 2. 设置选项
- curl_setopt($ch, CURLOPT_URL, "http://www.111cn.net");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- // 3. 执行并获取返回的内容
- $output = curl_exec($ch);
- // 4. 错误判断,注意这里是布尔值,而不是空输出,所以是3个等号
- if ($output === FALSE) {
- echo "cURL Error: " . curl_error($ch);
- }
- // 5. 释放curl资源
- curl_close($ch);
- // 输出获得的源代码
- echo $output;
- ?>
获取信息
这是另一个可选的设置项,能够在cURL执行后获取这一请求的有关信息,代码如下:
- <?php
- header("Content-type: text/html; charset=utf-8");
- // 1. 初始化
- $ch = curl_init();
- // 2. 设置选项
- curl_setopt($ch, CURLOPT_URL, "http://www.111cn.net");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- // 3. 执行并获取HTML文档内容
- $output = curl_exec($ch);
- // 4. 错误判断,注意这里是布尔值,而不是空输出,所以是3个等号
- if ($output === FALSE) {
- echo "cURL Error: " . curl_error($ch);
- }
- // 获取 cURL 信息 并输出
- $info = curl_getinfo($ch);
- echo '获取 '. $info['url'] . ' 耗时 '. $info['total_time'] . '秒';
- // 5. 释放curl句柄
- curl_close($ch);
- ?>
返回的数组中包括了以下信息:
- "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" // 重定向耗时
用POST方法发送数据,新建 from.php,代码如下:
- <?php
- header("Content-type: text/html; charset=utf-8");
- // 待 post 的数据
- $post_data = array (
- "hyh" => "man",
- "xlp" => "woman",
- "love" => "yes"
- );
- // 1. 初始化
- $ch = curl_init();
- // 2. 设置选项
- curl_setopt($ch, CURLOPT_URL, "http://localhost/to.php");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_POST, 1); // 这里设置为post方式
- curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // 添加准备post的数据
- // 3. 执行并获取返回内容
- $output = curl_exec($ch);
- // 4. 错误判断,注意这里是布尔值,而不是空输出,所以是3个等号
- if ($output === FALSE) {
- echo "cURL Error: " . curl_error($ch);
- }
- // 5. 释放curl句柄
- curl_close($ch);
- // 输出内容
- echo $output;
- ?>
新建to.php,代码如下:
- <?php
- header("Content-type: text/html; charset=utf-8");
- echo "从 from.php POST数据到 to.php 成功!以下为 to.php 返回的数据:<br><br>";
- print_r($_POST);
- echo "<br><br>I'm come from http://www.phpfensi.com"
- ?>
文件上传
上传文件和前面的POST十分相似,因为所有的文件上传表单都是通过POST方法提交的。
新建 from.php,代码如下:
- <?php
- header("Content-type: text/html; charset=utf-8");
- // 待 post 的数据
- $post_data = array (
- "hyh" => "man",
- "upload" => "@C:/test.zip" // 要上传的本地文件地址
- );
- // 1. 初始化
- $ch = curl_init();
- // 2. 设置选项
- curl_setopt($ch, CURLOPT_URL, "http://localhost/to.php");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_POST, 1); // 这里设置为post方式
- curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // 添加准备post的数据
- // 3. 执行并获取返回内容
- $output = curl_exec($ch);
- // 4. 错误判断,注意这里是布尔值,而不是空输出,所以是3个等号
- if ($output === FALSE) {
- echo "cURL Error: " . curl_error($ch);
- }
- // 5. 释放curl资源
- curl_close($ch);
- // 输出内容
- echo $output;
- ?>
新建 to.php,代码如下:
- <?php
- header("Content-type: text/html; charset=utf-8");
- print_r($_FILES);
- ?>
如果你需要上传一个文件,只需要把文件路径像一个post变量一样传过去,不过记得在前面加上@符号。
另一些有用的cURL范例
HTTP认证
如果某个URL请求需要基于 HTTP 的身份验证,你可以使用下面的代码:
- <?php
- header("Content-type: text/html; charset=utf-8");
- // 1. 初始化
- $ch = curl_init();
- // 2. 设置选项
- curl_setopt($ch, CURLOPT_URL, "http://www.111cn.net");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_USERPWD, "myusername:mypassword"); // 发送用户名和密码
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 你可以允许其重定向
- curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, 1); // 让 cURL 在重定向后,也能发送用户名和密码
- // 3. 执行并获取返回内容
- $output = curl_exec($ch);
- // 4. 错误判断,注意这里是布尔值,而不是空输出,所以是3个等号
- if ($output === FALSE) {
- echo "cURL Error: " . curl_error($ch);
- }
- // 5. 释放curl句柄
- curl_close($ch);
- ?>
FTP上传
PHP 自带有 FTP 类库,但你也能用 cURL,代码如下:
- <?php
- header("Content-type: text/html; charset=utf-8");
- // 开一个文件指针
- $file = fopen("/path/to/file", "r");
- // 1. 初始化
- $ch = curl_init();
- // 2. 设置选项
- curl_setopt($ch, CURLOPT_URL, "ftp://username:password@3aj.cn:21/path/to/new/file");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- // 上传相关的选项
- curl_setopt($ch, CURLOPT_UPLOAD, 1);
- curl_setopt($ch, CURLOPT_INFILE, $fp);
- curl_setopt($ch, CURLOPT_INFILESIZE, filesize("/path/to/file"));
- // 是否开启ASCII模式 (上传文本文件时有用)
- curl_setopt($ch, CURLOPT_FTPASCII, 1);
- // 3. 执行并获取返回内容
- $output = curl_exec($ch);
- // 4. 错误判断,注意这里是布尔值,而不是空输出,所以是3个等号
- if ($output === FALSE) {
- echo "cURL Error: " . curl_error($ch);
- }
- // 5. 释放curl句柄
- curl_close($ch);
- ?>
你可以用代理发起cURL请求,代码如下:
- <?php
- header("Content-type: text/html; charset=utf-8");
- // 1. 初始化
- $ch = curl_init();
- // 2. 设置选项
- curl_setopt($ch, CURLOPT_URL, "http://www.phpfensi.com");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_PROXY, '11.11.11.11:8080'); // 指定代理地址
- curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'user:pass'); // 如果需要的话,提供用户名和密码
- // 3. 执行并获取返回内容
- $output = curl_exec($ch);
- // 4. 错误判断,注意这里是布尔值,而不是空输出,所以是3个等号
- if ($output === FALSE) {
- echo "cURL Error: " . curl_error($ch);
- }
- // 5. 释放curl句柄
- curl_close($ch);
- ?>
回调函数
可以在一个URL请求过程中,让cURL调用某指定的回调函数,例如,在内容或者响应下载的过程中立刻开始利用数据,而不用等到完全下载完,实例代码如下:
- <?php
- header("Content-type: text/html; charset=utf-8");
- // 1. 初始化
- $ch = curl_init();
- // 2. 设置选项
- curl_setopt($ch, CURLOPT_URL, "http://www.111cn.net");
- curl_setopt($ch, CURLOPT_WRITEFUNCTION, "progress_function");
- // 3. 执行并获取返回内容
- curl_exec($ch);
- // 4. 错误判断,注意这里是布尔值,而不是空输出,所以是3个等号
- if ($output === FALSE) {
- echo "cURL Error: " . curl_error($ch);
- }
- // 5. 释放curl句柄
- curl_close($ch);
- // 回调函数
- function progress_function($ch, $str) {
- echo $str;
- return strlen($str);
- }
- ?>
这个回调函数必须返回字串的长度,不然此功能将无法正常使用,在URL响应接收的过程中,只要收到一个数据包,这个函数就会被调用。
讲到了半天我们再来一个高级实用点的功能cURL来实现ftp上传
web服务器的上传限制:
php的默认上传限制为2M,如果你要上传超过2M的文件的话,你必须修改你的PHP配置 或者 用下面的代码建立一个 .htaceess文件,代码如下:
php_value upload_max_filesize 16M
php_value post_max_size 20M
这里设置最大的文件上传限制为16M,post_max_size 的值为20M,因为可能在上传文件的同时,我们还需要POST表单里的其他表单项的值。
建立的 .htaccess 要放在你的上传脚本同一个目录下。
使用 cURL 进行文件上传
cURL 是一个利用URL语法规定来传输文件和数据的工具,支持很多种协议,如HTTP、FTP、TELNET等。它能完成很多高难度任务——如处理coockies、验证、表单提交、文件上传、ftp上传等等。
这里,我们准备通过使用web表单来上传一个文件到ftp空间上,这里的ftp空间是有密码保护的,代码如下:
- <form action="curlupload.php" method="post" enctype="multipart/form-data">
- <div>
- <label for="upload">Select file</label>
- <input name="upload" type="file" />
- <input type="submit" name="Submit" value="Upload" />
- </div>
- </form>
这个表单页面比较简单,仅仅是拥有一个文件上传的功能,然后我们需要下面的php代码来接收上传过来的文件,使用 cURL 打开一个文件流并传送到远程ftp服务器上去,实例代码如下:
- if (isset($_POST['Submit'])) {
- if (!emptyempty($_FILES['upload']['name'])) {
- $ch = curl_init();
- $localfile = $_FILES['upload']['tmp_name'];
- $fp = fopen($localfile, 'r');
- curl_setopt($ch, CURLOPT_URL, 'ftp://username:password@3aj.cn/'.$_FILES['upload']['name']);
- curl_setopt($ch, CURLOPT_UPLOAD, 1);
- curl_setopt($ch, CURLOPT_INFILE, $fp);
- curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
- curl_exec($ch);
- $error_no = curl_errno($ch);
- curl_close($ch);
- if ($error_no == 0) {
- $error = 'File uploaded succesfully.';
- } else {
- $error = 'File upload error.';
- echo "i come from ";
- }
- } else {
- $error = 'Please select a file.';
- }
- }
当用户选择了并上传了一个文件,文件先保存在web服务器上,我们使用 fopen 打开这个临时文件并初始一个cURL会话,在发送的url中,把ftp的账号和密码填上,然后再设置cURL的其他必备参数即可,如果返回的错误数量为0,那么文件就上传成功了。
波比源码 » php CURL函数入门教程详解
levaquin 500mg canada order levaquin 500mg without prescription
order avodart 0.5mg generic zofran online zofran 4mg tablet
aldactone 25mg generic spironolactone price fluconazole 100mg us
acillin brand purchase ampicillin without prescription buy erythromycin
fildena 100mg price order sildenafil 50mg online cheap order robaxin online
oral suhagra 50mg order aurogra 50mg sale buy estrace 1mg online cheap
oral lamictal purchase vermox sale order generic tretinoin gel
purchase tadalafil online cheap voltaren over the counter voltaren 50mg brand
cheap accutane amoxicillin 1000mg usa azithromycin ca
oral indomethacin 75mg amoxicillin cost trimox 250mg without prescription
cialis 5mg sans ordonnance en pharmacie tadalafil 5mg en france viagra generique
prednisone 10mg cost buy prednisone online viagra 50mg oral
tadalafil ohne rezept cialis bestellen original viagra 50mg rezeptfrei sicher kaufen
order buspar 5mg online dilantin 100mg drug order ditropan 2.5mg without prescription
fosamax pills purchase fosamax without prescription famotidine over the counter
order olmesartan 10mg without prescription buy benicar 10mg pills buy acetazolamide 250mg online
tacrolimus ca generic prograf 1mg ursodiol us
order imdur 20mg online order imdur 20mg online cheap telmisartan 20mg for sale
purchase zyban online cheap order quetiapine 100mg pill seroquel tablet
buy molnupiravir 200mg pill order molnupiravir 200mg online buy prevacid 30mg pill
zoloft online order lexapro 10mg canada viagra pills
order medroxyprogesterone 10mg pills hydrochlorothiazide canada buy cyproheptadine 4 mg generic
isotretinoin 40mg brand buy prednisone 20mg sale buy prednisone 10mg generic
azithromycin tablet order prednisolone 20mg online buy gabapentin 800mg online
cialis tadalafil tadalafil 10mg generic anafranil drug
buy aralen chloroquine 250mg generic olumiant cost
brand metformin lipitor medication tadalafil 40mg brand
cheap amlodipine 5mg purchase tadalafil online cheap generic cialis cost
cheap clozaril 100mg clozapine 50mg canada decadron 0,0,5 mg brand
buy omeprazole 20mg generic omeprazole generic roulette free play for fun
buy generic metoprolol 50mg buy atenolol pills levitra brand
essay helpers casino games gambling addiction
levitra 10mg pills order levitra methylprednisolone 8 mg online
buy zyloprim 100mg online cheap buy rosuvastatin 20mg pill ezetimibe over the counter
buy motilium 10mg pill purchase tetracycline online cheap flexeril 15mg cost
order generic losartan losartan pills buy topamax 200mg for sale
purchase lioresal buy tizanidine generic buy toradol 10mg online cheap
colchicine 0.5mg us colchicine drug casino slot games
live blackjack online casino real money real casinos online no deposit
brand cialis 40mg cialis 40mg cheap cipro sale
buy fluconazole 200mg pills diflucan 200mg over the counter order viagra 50mg pill
canadian viagra and healthcare buy sildenafil for sale order tadalafil 5mg for sale
trazodone 50mg pill trazodone online buy sildenafil brand
order prednisone generic order isotretinoin 40mg generic amoxicillin
order sildenafil 50mg without prescription sildenafil for men tadalafil 5mg brand
azithromycin ca order prednisolone online oral gabapentin
casino game purchase provigil generic buy provigil 200mg generic
order fildena pills fildena 100mg drug purchase budesonide pills
retin price order tadalis 20mg for sale avanafil 200mg oral
terbinafine medication order trimox 250mg sale order trimox 250mg generic
proventil 100 mcg usa buy generic pantoprazole 20mg buy ciprofloxacin pill
buy singulair pill montelukast 10mg for sale order viagra 50mg online
buy doxycycline 100mg generic cleocin 300mg cheap cleocin 150mg brand
buy asacol pills azelastine for sale online irbesartan uk
order temovate online cheap generic amiodarone 100mg buy cordarone 100mg pills
amoxil 250mg over the counter stromectol price ivermectin cost canada
buy carvedilol 6.25mg buy carvedilol generic elavil over the counter
generic indomethacin 75mg order indomethacin 50mg for sale cenforce 100mg uk
doxycycline uk order doxycycline 100mg generic buy medrol 16mg online
purchase tadacip plavix 150mg brand trimox for sale
order minocycline 50mg online cheap order hytrin 1mg pill buy terazosin
buy glycomet without prescription order generic nolvadex 20mg nolvadex order online
cheap clomiphene prednisolone cost prednisolone 5mg us
purchase prednisone generic buy generic accutane 10mg buy amoxicillin 500mg pill
erectile dysfunction medicines buy generic proscar 1mg order finasteride 1mg pill
ivermectin 6 mg otc generic deltasone 10mg order deltasone 10mg pill
buy prednisolone tablets oral neurontin 100mg furosemide 40mg sale
order vibra-tabs generic order acyclovir 400mg pills generic acyclovir 400mg
cost cefdinir 300 mg cefdinir 300 mg sale pantoprazole ca
purchase zocor generic buy phenergan online cheap purchase sildalis
uroxatral 10 mg pill buy alfuzosin 10mg without prescription buy diltiazem 180mg
brand coumadin allopurinol 300mg price zyloprim cost
order generic cenforce 100mg order glucophage 500mg online cheap brand glycomet 500mg
order atorvastatin 80mg without prescription lipitor pills viagra order
femara pill viagra 100mg for sale sildenafil 50mg price
tadalafil 10mg us cost cialis 5mg buy ed medications online
order tadalafil 40mg for sale cheap tadalafil for sale buy ed pills uk
buy modafinil 100mg without prescription modafinil brand buy prednisone cheap
amoxicillin 500mg without prescription order prednisolone how to buy prednisolone
albuterol online buy albuterol 4mg canada cheap levoxyl tablets
order generic clomiphene order plaquenil pills hydroxychloroquine 200mg us
buy atenolol tablets femara generic order letrozole 2.5 mg pills
buy methotrexate 5mg methotrexate 5mg generic buy generic metoclopramide
purchase tetracycline pills flexeril tablet buy baclofen 25mg online
order toradol for sale toradol 10mg price generic inderal 10mg
clopidogrel 150mg canada fluvoxamine us order ketoconazole
flomax us purchase zofran pill spironolactone 25mg pill
brand duloxetine piracetam 800 mg over the counter purchase piracetam generic
order progesterone generic zyprexa 10mg generic order olanzapine 10mg without prescription
buy zocor no prescription simvastatin online buy purchase sildenafil sale
cefadroxil 500mg usa proscar 5mg price buy propecia pill
fluconazole 200mg uk acillin canada cipro 500mg pill
order estradiol 1mg online cheap buy lamictal 200mg minipress usa
buy cleocin 150mg online ed pills that really work blue pill for ed
order avanafil generic order voltaren 50mg for sale cambia brand
tamoxifen 20mg tablet buy tamoxifen 20mg sale ceftin 500mg sale
order indocin 50mg online cheap indomethacin price cheap suprax 100mg
buy trimox no prescription clarithromycin online buy buy cheap generic clarithromycin
clonidine 0.1mg tablet purchase tiotropium bromide pill order spiriva 9mcg pills
minocin 50mg oral cost pioglitazone 30mg buy actos 30mg pill
purchase absorica pills buy amoxicillin 500mg sale order zithromax 500mg without prescription
tadalafil 5mg generic cheap tadalafil pill order tadalafil pills
ivermectin 6 mg for people order stromectol 12mg cheap deltasone 20mg
order levitra 20mg for sale buy levitra pill plaquenil price
vardenafil 10mg ca tizanidine 2mg without prescription buy hydroxychloroquine 400mg online
order ramipril 5mg without prescription glimepiride pill cheap arcoxia 120mg
order asacol sale buy mesalamine generic avapro 150mg brand
buy carvedilol 6.25mg online cheap cenforce over the counter generic aralen
order lanoxin 250mg sale buy digoxin medication buy molnupiravir online
naprosyn price order lansoprazole pills prevacid buy online