天天看點

php curl上傳檔案$_FILES為空問題

php使用curl上傳檔案,代碼如下:

發送的代碼(完全是官方的示例)

<?php

$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

$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

$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);

?>

相關文章:

php curl檔案上傳相容php5.0~5.6各版本

http://www.cnblogs.com/zqifa/p/php-curl-2.html