【捷哥浅谈PHP】第十六弹—文件传输工具cURL的高级应用

2012 年 9 月 6 日6760

我们接着上文的内容来讲,上文给大家简单介绍了下使用curl的四个步骤,本文来给大家讲解下curl的一些高级应用:

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

    ?>

    打印出来的内容为:

    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数据的页面:

再新建一个页面,用来模拟浏览器发送POST数据:

    ?>
    打印出来的结果:

    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

upload.php

    ?>

    传递回来的值:

    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

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

cURL批处理:

cURL还有一个高级应用,批处理句柄,这个特性可以同步或异步地处理多个URL连接:

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

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

原文地址:http://bbs.lampbrother.net/read-htm-tid-121356.html

0 0