PHP cURL模块
简介:
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值了;还可以实现上传文件的功能等等。

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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











There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.
