博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
curl操作和file_get_contents() 比较
阅读量:4610 次
发布时间:2019-06-09

本文共 2173 字,大约阅读时间需要 7 分钟。

1 . curl需要php开启php_curl开启扩展

$ch = curl_init();

$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, 'http://www.baidu.com');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);

echo $file_contents;

 

2.file_get_contents()把php的allow_url_fopen选项是必须是开启。

 echo $content= file_get_contents("http://www.baidu.com");

 

总结:

基于2者的启用条件,需要利用function_exists函数来判断php是否支持一个函数可以轻松写出下面函数。

 

下面简单介绍curl:

curl是一个利用URL语法规定来传输文件和数据的工具,支持很多协议,如HTTP、FTP、TELNET等。

$info = curl_getinfo($ch);

 得到的是一个数组:

返回的数组中包括了以下信息:

  • “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实现http的一些请求:

用POST方法发送数据    

接下来,写一段PHP脚本来执行cURL请求:

 

 

以下为引用的内容:

$url = "http://localhost/post_output.php";

$post_data = array (
    "foo" => "bar",
    "query" => "Nettuts",
    "action" => "Submit"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 我们在POST数据哦!
curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
echo $output;

 文件上传:

上传文件和前面的POST十分相似。因为所有的文件上传表单都是通过POST方法提交的。

首先新建一个接收文件的页面,命名为 upload_output.php:

print_r($_FILES);

以下是真正执行文件上传任务的脚本:

 

以下为引用的内容:

$url = "http://localhost/upload_output.php";

$post_data = array (
    "foo" => "bar",
    // 要上传的本地文件地址
    "upload" => "@C:/wamp/www/test.zip"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
echo $output;

 

如果你需要上传一个文件,只需要把文件路径像一个post变量一样传过去,不过记得在前面加上@符号。执行这段脚本应该会得到如下输出:

 

转载于:https://www.cnblogs.com/legend-song/p/3741677.html

你可能感兴趣的文章
【Python使用】使用pip安装卸载Python包(含离线安装Python包)未完成???
查看>>
一语道破项目管理知识体系五大过程组
查看>>
C# 备份、还原、拷贝远程文件夹
查看>>
在windows环境下运行compass文件出现的错误提示解决方案
查看>>
CSS常用样式--font
查看>>
恩如氏--蜗牛精华补水蚕丝面膜
查看>>
大工具-收藏
查看>>
codevs3027 线段覆盖 2
查看>>
markdown
查看>>
【leetcode】107-Binary Tree Level Order Traversal II
查看>>
Jquert data方法获取不到数据,显示为undefined。
查看>>
ssm项目中 数据库和资源的备份
查看>>
HDU5950【矩阵快速幂】
查看>>
在线C++编译器
查看>>
C#中各种serialization的比较
查看>>
P2617 Dynamic Rankings
查看>>
工作学习常识1
查看>>
Eclipse插件项目中读取文件
查看>>
jquery定义链接跳转的高亮显示
查看>>
CheckListBox怎样得到多选值?
查看>>