search

简介:

     cURL是利用URL语法在命令行方式下工作的文件传输工具,目前苹果机器已经内置了cURL。cURL是一个综合性的传输工具,对HTTP、FTP等协议提供了广泛的支持,它甚至可以实现迅雷、快车等下载工具的所有功能。PHP中也提供了对cURL语法的支持。

  PHP支持的由Daniel Stenberg创建的libcurl库允许你与各种的服务器使用各种类型的协议进行连接和通讯。libcurl目前支持http、https、ftp、gopher、telnet、dict、file和ldap协议。libcurl同时也支持HTTPS认证、HTTP POST、HTTP PUT、 FTP 上传(这个也能通过PHP的FTP扩展完成)、HTTP 基于表单的上传、代理、cookies和用户名+密码的认证。

 

为什么需要cURL: 

  一般读取文件(URL)的方法是使用PHP内置的一些读文件函数,比如file_get_contents,file等(参见文章《PHP读取文件的常见方法》);但是这些方法都只能进行简单的文件读取,不能实现复杂的功能:向URL POST数据、使用代理服务器、读取使用SSL协议的URL、URL登陆认证等。而cURL恰恰提供了对这些功能的支持。

 

开启方法: 拷贝PHP目录中的libeay32.dll 和 ssleay32.dll 两个文件到 C:\windows\system32 目录。  修改php.ini。去掉 extension = php_curl.dll 前面的分号。 重启Apache服务 查看phpinfo,可以看到curl已开启

 

建立cURL请求的基本步骤:     1. 初始化

    使用curl_init方法初始化一个cURL句柄

  $ch = curl_init("http://www.example.com/");

  curl_init方法提供了一个可选参数URL,返回一个cURL句柄供curl_setopt(), curl_exec()和curl_close() 函数使用。

  如果在curl_init中没有指定URL,则需要在curl_setopt中手工设置这个值,如果指定了URL,则CURLOPT_URL被自动设成这个值。

  2. 设置变量

    使用curl_setopt方法设置一个cURL传输参数,或者使用curl_setopt_array批量设置一组参数。

    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);

    其中$ch为curl_init初始化时返回的cURL句柄。

    3. 执行并获取结果

    使用curl_exec执行一个cURL会话,成功时返回 TRUE, 或者在失败时返回 FALSE. 然而,如果 CURLOPT_RETURNTRANSFER选项被设置,函数执行成功时会返回执行的结果,失败时返回 FALSE 。

    curl_exec($ch);

    还可以使用curl_getinfo获取一个cURL会话的信息。

    curl_getinfo($info);

    curl_getinfo返回的数组中包括如下信息:

"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"//重定向耗时     4. 关闭cURL会话

    使用curl_close关闭cURL会话,并释放所有资源(包括cURL句柄$ch等)。

    curl_close($ch);

  

  一个完整的例子如下:

<?php    // 1. 初始化    $ch = curl_init("http://www.baidu.com");    // 2. 设置选项    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  //将curl_exec()获取的信息以文件流的形式返回,而不是直接输出,如果没有设置CURLOPT_RETURNTRANSFER,curl_exec($ch)将直接输出返回内容。
 // 3. 执行会话并获取内容    $output = curl_exec($ch);  //或者使用curl_multi_getcontent()获取会话返回的内容    echo $output;    $info = curl_getinfo($ch);    print_r($info);    // 4. 关闭curl会话    curl_close($ch);?>



  当然我们还可以使用curl_error来获取会话的错误信息。

if($output === false)//注意是三个等号,表示检查返回值是boolean类型,如果是两个等号,返回值为空字符串也会被认为是false    echo 'cURL error:'.curl_error($ch);

  例如,我们直接访问支付宝的首页,由于支付宝首页基于SSL协议,直接访问会提示证书错误:

cURL error:SSL certificate problem, verify that the CA cert is OK. Details:error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

 

 

使用代理服务器

<?php    // 1. 初始化    $ch = curl_init("http://www.baidu.com");    // 2. 设置代理服务器    curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');    // 3. 执行会话    curl_exec($ch);    // 4. 关闭curl会话    curl_close($ch);?>


向URL POST数据

<?php    //POST数据    $curlPost = array(        'name'=>'myname',        'pwd'=>'mypassword'    );    //或者 $curlPost = 'name=myname&pwd=mypassword';
  //初始化    $ch = curl_init("http://localhost/SP/getpost.php");    //设置    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    curl_setopt($ch, CURLOPT_POST, 1);    //设施post方式提交数据    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);    //设置POST的数据    //执行会话并获取内容    $output = curl_exec($ch);    echo $output;    //关闭curl会话    curl_close($ch);?>


使用浏览器用户代理

<?php    // 1. 初始化    $ch = curl_init("http://www.baidu.com");    // 2. 设置    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    //设置User-Agent为iPhone下的Safafi    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A537a Safari/419.');    // 3. 执行会话并获取内容    $output = curl_exec($ch);    echo $output;    // 4. 释放curl句柄    curl_close($ch);?>


访问SSL协议的URL

<?php    // 1. 初始化    $ch = curl_init("https://www.alipay.com");    // 2. 设置    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//使用服务器端验证    curl_setopt($ch, CURLOPT_USERPWD, "myusername:mypassword");//设置登录用户名和密码    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);//允许服务器端重定向    // 3. 执行会话并获取内容    $output = curl_exec($ch);    echo $output;    // 4. 释放curl句柄    curl_close($ch);?>

 

cURL还有很多其他的实际用途,比如检查你博客的友情链接是否都有效,这里就需要用到curl_getinfo()函数返回的http_code值了;还可以实现上传文件的功能等等。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

How do you optimize PHP applications for performance?How do you optimize PHP applications for performance?May 08, 2025 am 12:08 AM

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools