avatar

curl上传文件$_FILES为空问题

php使用curl上传文件

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php

/* http://devtest.com/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://devtest.com/load_file.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>

接收代码:

1
2
3
<?php
print_r($_POST);
print_r($_FILES);

运行结果:

1
2
3
4
5
6
7
8
9
php -f demo.php
Array
(
[name] => Foo
[file] => @/home/vagrant/test.png
)
Array
(
)

这时我们发现 通过 curl 发送的文件 在另一边 $_FILES 接受不到

解决方法1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php

/* http://devtest.com/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://devtest.com/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版本下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php

/* http://devtest.com/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://devtest.com/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);
?>

最后附上完整代码

使用时建议配上域名单独使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
// var_dump(file_get_contents('php://input'));die;
var_dump($_FILES);
exit(1);
}elseif ($_SERVER['REQUEST_METHOD'] == 'GET') {
$str = <<<EOT
<center><h1>curl 文件上传测试demo</h1></center>
EOT;
echo $str;
exit(1);
}

function ceshi()
{
$ch = curl_init();

$data = array('name' => 'Foo', 'file' => new \CURLFile('/Users/higanbana/Desktop/GM8A78.png'));


curl_setopt($ch, CURLOPT_URL, 'http://devtest.com/fileTest.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

return curl_exec($ch);
}

var_dump(ceshi()); // version php 7.3.11
文章作者: Depravity-pig
文章链接: https://magicconch17.github.io/2020/04/09/php-curl%E4%B8%8A%E4%BC%A0%E6%96%87%E4%BB%B6%E4%B8%BA%E7%A9%BA%E9%97%AE%E9%A2%98/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Cat at ngint
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论