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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools