php curl 上傳文件代碼實(shí)例

字號(hào):


    這篇文章主要介紹了php curl 上傳文件代碼實(shí)例,本文給出了兩種實(shí)現(xiàn)方法,并分別給出了實(shí)現(xiàn)代碼,需要的朋友可以參考下
    假設(shè)server端上傳文件處理腳本upload.php:
    代碼如下:
    print_r($_POST);
    print_r($_FILES);
    1、使用 CURL 默認(rèn)的方法
    代碼如下:
    //如果php文件是utf8編碼,系統(tǒng)是GBK編碼,那么就需要轉(zhuǎn)下編碼,要不然Php在系統(tǒng)中找不到這個(gè)文件
    $file = realpath(mb_convert_encoding('測(cè)試圖片.JPG','GBK','utf8'));
    $file = realpath('temp.jpg'); //要上傳的文件
    $fields['f'] = ; // 前面加@符表示上傳圖片
    $ch =curl_init();
    curl_setopt($ch,CURLOPT_URL,'http://localhost/upload.php');
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    $content = curl_exec($ch);
    echo $content;
    2、另類的做法,有時(shí)我們需要將動(dòng)態(tài)產(chǎn)生的內(nèi)容當(dāng)做文件上傳到遠(yuǎn)程服務(wù)器,卻又不想在本地服務(wù)器中構(gòu)建臨時(shí)文件。這樣就有了這個(gè)另類的寫法
    代碼如下:
    $contents =<<< 'TEXT'
    這里是文件內(nèi)容,也可以是圖片二進(jìn)制,圖片需要修改上傳文件類型
    TEXT;
    $varname = 'my';//上傳到$_FILES數(shù)組中的 key
    $name = '3.txt';//文件名
    $type = 'text/plain';//文件類型
    $key = "$varname\"; filename=\"$name\r\nContent-Type: $type\r\n";
    $fields[$key] = $contents;
    $ch =curl_init();
    curl_setopt($ch,CURLOPT_URL,'http://localhost/upload.php');
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    $content = curl_exec($ch);
    echo $content;