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