《PHP學習:php curl 上傳文件代碼實例》要點:
本文介紹了PHP學習:php curl 上傳文件代碼實例,希望對您有用。如果有疑問,可以聯系我們。
假設server端上傳文件處理腳本upload.php:
PHP應用
代碼如下:
<?php?
?
print_r($_POST);?
print_r($_FILES);?
1、使用 CURL 默認的辦法
代碼如下:
//如果php文件是utf8編碼,系統是GBK編碼,那么就需要轉下編碼,要不然Php在系統中找不到這個文件???
$file = realpath(mb_convert_encoding('測試圖片.JPG','GBK','utf8'));?
?
$file = realpath('temp.jpg'); //要上傳的文件???
$fields['f'] = '@'.$file; // 前面加@符表示上傳圖片??
?
$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、另類的做法,有時我們需要將動態產生的內容當做文件上傳到遠程服務器,卻又不想在本地服務器中構建臨時文件.這樣就有了這個另類的寫法
代碼如下:
$contents =<<< 'TEXT'?
這里是文件內容,也可以是圖片二進制,圖片需要修改上傳文件類型?
TEXT;?
?
$varname = 'my';//上傳到$_FILES數組中的 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;?
《PHP學習:php curl 上傳文件代碼實例》是否對您有啟發,歡迎查看更多與《PHP學習:php curl 上傳文件代碼實例》相關教程,學精學透。維易PHP學院為您提供精彩教程。
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/10973.html