1. 程式人生 > >php curl上傳檔案

php curl上傳檔案

PHP5.6之前實現
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
        )

)



cURL 上傳檔案在檔名(不能有中文)前加個@符號,然後用$_FILES接收檔案。

5.5.0及以後的實現,

<?php
$data = array('name'=>'Foo','file'=>'');

    $ch = curl_init(); 

    $data['file']=new CURLFile(realpath(getcwd().'/test.png'));

    curl_setopt($ch, CURLOPT_URL, "http://localhost/upload.php");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); 
    curl_setopt($ch, CURLOPT_POSTFIELDS , $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

    $output = curl_exec($ch); 

    echo $output;

    curl_close($ch);