php5.5.9 curl 上传文件

63 篇文章 0 订阅

发现我的个人网站开启了curl 但是无法对外连接任何端口,所以还是有方法的http://,使用vps搭建临时的服务器,使用php curl 上传文件到服务器

使用网上的样例出现

Deprecated: curl_setopt(): The usage of the @filename API for file uploading is deprecated. Please use the CURLFile class instead in/usr/local/apache2/htdocs/T1/php_curl_up1_1.php on line41
 

好吧,这个是版本问题导致的

于是找到了最新的在线文档说明和例子

http://www.php.net/manual/zh/function.curl-setopt.php

范例

Example #1 初始化一个新的cURL会话并获取一个网页

<?php
// 创建一个新cURL资源
$ch =curl_init();

// 设置URL和相应的选项
curl_setopt($ch,CURLOPT_URL,"http://www.example.com/");
curl_setopt($ch,CURLOPT_HEADER,false);

// 抓取URL并把它传递给浏览器
curl_exec($ch);

//关闭cURL资源,并且释放系统资源
curl_close($ch);
?>

Example #2 上传文件

<?php

/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/

$ch =curl_init();

$data = array('name'=>'Foo','file'=>'@/home/user/test.png');

curl_setopt($ch,CURLOPT_URL,'http://localhost/upload.php');
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);

curl_exec($ch);
?>

以上例程会输出:

Array
(
    [name] => Foo
)
Array
(
    [file] => Array
        (
            [name] => test.png
            [type] => image/png
            [tmp_name] => /tmp/phpcpjNeQ
            [error] => 0
            [size] => 279
        )

)

注释

Note:

传递一个数组到CURLOPT_POSTFIELDS,cURL会把数据编码成multipart/form-data,而然传递一个URL-encoded字符串时,数据会被编码成application/x-www-form-urlencoded


于是我照葫芦画瓢:

上传文件的文件

<?php
// Path to the file we want to upload
$uploaddir = getcwd();
$file = $uploaddir."/9N0CB31K28JU0007.jpg"; //这里非常重要!一定要绝对地址才行,所以使用这个拼接成了绝对地址


// Create a cURL handle
$ch = curl_init('http://192.168.5.41/T1/up2.php');


// Create a CURLFile object
$cfile = curl_file_create($file);


// Assign POST data
$data = array('fff' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_setopt($ch, CURLOPT_INFILESIZE,filesize($file)); //这句非常重要,告诉远程服务器,文件大小,查到的是前辈的文章http://blog.csdn.net/cyuyan112233/article/details/21015351


// Execute the handle
curl_exec($ch);




?> 






接收文件的文件内容

<?php
print_r($_FILES);
$uploaddir = getcwd().'/tmp/'; //a directory inside 
echo $uploaddir."<br />";
echo $_FILES["fff"]["name"]."<br />";
$file_name=basename($_FILES["fff"]["name"]);
echo $file_name."<br />";
move_uploaded_file($_FILES['fff']['tmp_name'],$uploaddir.$file_name);


//测试是否有写入权限
//$fp=fopen("tmp.txt","wb");
//fwrite($fp,"abc\r\n");
//fclose($fp);
?>



这样就可以啦!~~哈哈~

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值