search
HomeBackend DevelopmentPHP Tutorial 【捷哥浅谈PHP】第十六弹-文件传输工具cURL的高级使用

【捷哥浅谈PHP】第十六弹---文件传输工具cURL的高级应用
我们接着上文的内容来讲,上文给大家简单介绍了下使用curl的四个步骤,本文来给大家讲解下curl的一些高级应用:

获取请求的相关信息,我们可以在curl执行完成后利用curl_getinfo():

  1. // 创建一个新cURL资源
  2. $ch = curl_init("http://www.lampbrother.net");
  3. // 设置URL和相应的选项
  4. curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  5. // 检查是否有错误发生
  6. if(!curl_errno($ch))
  7. {
  8. $info = curl_getinfo($ch);
  9. var_dump($info);
  10. }
  11. // 抓取URL并把它传递给浏览器
  12. $html = curl_exec($ch);
  13. // 关闭cURL资源,并且释放系统资源
  14. curl_close($ch);
  15. ?>

    打印出来的内容为:

    array
    'url' => string 'http://www.lampbrother.net' (length=26)
    'content_type' => null
    'http_code' => int 0
    'header_size' => int 0
    'request_size' => int 0
    'filetime' => int 0
    'ssl_verify_result' => int 0
    'redirect_count' => int 0
    'total_time' => float 0
    'namelookup_time' => float 0
    'connect_time' => float 0
    'pretransfer_time' => float 0
    'size_upload' => float 0
    'size_download' => float 0
    'speed_download' => float 0
    'speed_upload' => float 0
    'download_content_length' => float -1
    'upload_content_length' => float -1
    'starttransfer_time' => float 0
    'redirect_time' => float 0
    'certinfo' =>array
    empty
    'redirect_url' => string '' (length=0)

    返回的数组中包括了以下信息:
    “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”//重定向耗时

    我们甚至可以通过curl来模拟浏览器用POST方式发送数据:

    我们先来建立一个可以打印POST数据的页面:
  1. var_dump($_POST);
  2. ?>
再新建一个页面,用来模拟浏览器发送POST数据:
  1. $url = "http://localhost/post.php";
  2. $post_data = array(
  3. "author"=>"李捷",
  4. "title"=>"捷哥浅谈PHP"
  5. );
  6. //初始化,创建一个新cURL资源
  7. $ch = curl_init();
  8. //设置URL和相应的选项
  9. curl_setopt($ch,CURLOPT_URL,$url);
  10. curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  11. curl_setopt($ch,CURLOPT_POST,1);
  12. curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
  13. //抓取URL并把它传递给浏览器
  14. $out = curl_exec($ch);
  15. //关闭cURL资源,并且释放系统资源
  16. curl_close($ch);
  17. echo $output;
  18. ?>
    打印出来的结果:

    array
    'author' => string '李捷' (length=4)
    'title' => string '捷哥浅谈PHP' (length=11)


    我们可以看到强大的curl已经帮我们把post数据传递过来了,它是这样一个过程:

    1.把post数据传递给post.php页面
    2.post.php页面将post数据输出显示在页面上
    3.curl将post.php接收并打印出的post数据抓取回来,输出在页面上!

    我们不仅能使用post传递数据,我们还可以上传文件,方法基本相同:


    curl.php
  1. $url = "http://localhost/upload.php";
  2. $post_data = array(
  3. "title"=>"惊艳!!!",
  4. "pic"=>"@d:\李文凯唯美艳照.jpg"
  5. );
  6. //初始化,创建一个新cURL资源
  7. $ch = curl_init();
  8. //设置URL和相应的选项
  9. curl_setopt($ch,CURLOPT_URL,$url);
  10. curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  11. curl_setopt($ch,CURLOPT_POST,1);
  12. curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
  13. //抓取URL并把它传递给浏览器
  14. $out = curl_exec($ch);
  15. //关闭cURL资源,并且释放系统资源
  16. curl_close($ch);
  17. echo $output;
  18. ?>

upload.php
  1. var_dump($_FILES);
  2. ?>

    传递回来的值:

    array
    'pic' =>array
    'name' => string '李文凯唯美艳照.jpg' (length=18)
    'type' => string 'application/octet-stream' (length=24)
    'tmp_name' => string 'F:\LAMPBrother\Environmental\wamp_32\tmp\php9A73.tmp' (length=52)
    'error' => int 0
    'size' => int 0
  1. $post_data = array(
  2. "title"=>"惊艳!!!",
  3. "pic"=>"@d:\李文凯唯美艳照.jpg"
  4. );

上传需要注意的是,要上传的文件名之前要加上@符号!

cURL批处理:

cURL还有一个高级应用,批处理句柄,这个特性可以同步或异步地处理多个URL连接:
  1. // 创建一对cURL资源
  2. $ch1 = curl_init();
  3. $ch2 = curl_init();
  4. // 设置URL和相应的选项
  5. curl_setopt($ch1, CURLOPT_URL, "http://www.li-jie.me/");
  6. curl_setopt($ch1, CURLOPT_HEADER, 0);
  7. curl_setopt($ch2, CURLOPT_URL, "http://www.lampbrother.net/");
  8. curl_setopt($ch2, CURLOPT_HEADER, 0);
  9. // 创建批处理cURL句柄
  10. $mh = curl_multi_init();
  11. // 增加2个句柄
  12. curl_multi_add_handle($mh,$ch1);
  13. curl_multi_add_handle($mh,$ch2);
  14. $running=null;
  15. // 执行批处理句柄
  16. do {
  17. usleep(10000);
  18. curl_multi_exec($mh,$running);
  19. } while ($running > 0);
  20. // 关闭全部句柄
  21. curl_multi_remove_handle($mh, $ch1);
  22. curl_multi_remove_handle($mh, $ch2);
  23. curl_multi_close($mh);
  24. ?>

$running会收集来自http://www.li-jie.me和http://www.lampbrother.net的页面内容,实现多个URL的批量处理!

大家看到了吧,以后采集网站摒弃file_get_contents和fopen吧,把我们强大的cURL用起来,会帮你的web应用增色不少!


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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)