php curl上传文件$_FILES为空问题

php使用curl上传文件,代码如下:

发送的代码(完全是官方的示例)

<?php

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

$ch = curl_init();

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

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

curl_exec($ch);
?>

接收代码(也是官方的)

<?php
print_r($_POST);
print_r($_FILES);

运行结果

php -f demo.php
Array
(
[name] => Foo
[file] => @/home/vagrant/test.png
)
Array
(
)

解决方法1:

<?php

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

$ch = curl_init();

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

curl_setopt($ch, CURLOPT_URL, 'http://localhost/test/curl/load_file.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>

解决方法2:
5.6版本下

<?php

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

$ch = curl_init();

$data = array('name' => 'Foo', 'file' => new \CURLFile(realpath('/home/vagrant/test.png')));

curl_setopt($ch, CURLOPT_URL, 'http://localhost/test/curl/load_file.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>

出处:www.l1mn.com

原文标题:php curl上传文件$_FILES为空问题

原文地址:https://www.l1mn.com/p/ezh5o3.html

本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。

分类:phpcurl
标签:phpcurl
评论

皖ICP备2023023451号

Copyright © L1MN.COM 联系方式:l1mnfw@163.com